Skip to content

Commit

Permalink
🐛 Fix relations bug
Browse files Browse the repository at this point in the history
  • Loading branch information
marcreichel committed Sep 3, 2023
1 parent 385feec commit 5b9ebd8
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"type": "library",
"minimum-stability": "dev",
"require": {
"php": "^8.0.2",
"php": "^8.1",
"laravel/framework": "^8.40.0|^9.0|^10.0",
"guzzlehttp/guzzle": "~6.0|~7.0",
"nesbot/carbon": "^2.53.1",
Expand Down
14 changes: 8 additions & 6 deletions src/Models/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -248,14 +248,16 @@ protected function setAttributes(array $attributes): void
protected function setRelations(array $attributes): void
{
$this->relations = collect($attributes)
->diffKeys($this->attributes)->map(function ($value, $key) {
if (is_array($value)) {
->filter(fn ($value, $key) => array_key_exists($key, $this->casts))
->map(function ($value, $key) {
if (is_array($value) && array_is_list($value)) {
return collect($value)->map(function ($value) use ($key) {
return $this->mapToModel($key, $value);
});
})->filter();
}
return $this->mapToModel($key, $value);
});
})
->filter(fn (mixed $value): bool => $value instanceof Model || ($value instanceof \Illuminate\Support\Collection && !$value->isEmpty()));
}

/**
Expand Down Expand Up @@ -317,7 +319,7 @@ private function mapToModel(string $property, mixed $value): mixed
return $value;
}

if (is_object($value)) {
if (is_array($value) && !array_is_list($value)) {
$properties = $this->getProperties($value);

return new $class($properties);
Expand All @@ -335,7 +337,7 @@ private function mapToModel(string $property, mixed $value): mixed
})->toArray();
}

return [];
return null;
}

/**
Expand Down

0 comments on commit 5b9ebd8

Please sign in to comment.