Skip to content

Commit

Permalink
casts the attribute before creating an instance when retrieved from R…
Browse files Browse the repository at this point in the history
…edis
  • Loading branch information
alvin0 committed Oct 26, 2023
1 parent f9c3f5f commit 12b50c3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/Builder.php
Expand Up @@ -210,7 +210,7 @@ public function get()
$models = [];

foreach ($this->getRepository()->fetchHashDataByPattern($this->getHashPattern()) as $hash => $attributes) {
$models[] = $this->model->newInstance($attributes, true, $hash)->syncOriginal();
$models[] = $this->model->newInstance($attributes, true, $hash, true)->syncOriginal();
}

return $this->getModel()->newCollection($models);
Expand Down Expand Up @@ -321,7 +321,7 @@ function ($keys) use ($callback, $resultData) {
// Fetch the attributes of the models in the current chunk, and create new model instances with
// these attributes
foreach ($this->getRepository()->fetchProperByListHash($keys) as $hash => $attributes) {
$modelsChunk[] = $this->model->newInstance($attributes, true, $hash)->syncOriginal();
$modelsChunk[] = $this->model->newInstance($attributes, true, $hash, true)->syncOriginal();
}

$resultData->push($modelsChunk);
Expand Down
13 changes: 11 additions & 2 deletions src/Model.php
Expand Up @@ -846,9 +846,10 @@ public function newBuilder($connection)
* @param array $attributes
* @param bool $exists
* @param string $redisKey
* @param bool $isCastAttribute
* @return static
*/
public function newInstance($attributes = [], $exists = false, string $redisKey = null)
public function newInstance($attributes = [], $exists = false, string $redisKey = null, $isCastAttribute = false)
{
// This method just provides a convenient way for us to generate fresh model
// instances of this current model. It is particularly useful during the
Expand All @@ -865,7 +866,15 @@ public function newInstance($attributes = [], $exists = false, string $redisKey

$model->mergeCasts($this->casts);

$model->fill((array) $attributes);
if ($isCastAttribute) {
$castAttributes = collect($attributes)->mapWithKeys(function ($value, $key) use ($model) {
return [$key => $model->transformModelValue($key, $value)];
})->all();

$model->fill((array) $castAttributes);
} else {
$model->fill((array) $attributes);
}

return $model;
}
Expand Down

0 comments on commit 12b50c3

Please sign in to comment.