From 5b9ebd853ccfeb31628453e9c46470b5499cd94b Mon Sep 17 00:00:00 2001 From: Marc Reichel Date: Sun, 3 Sep 2023 22:58:53 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20relations=20bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 2 +- src/Models/Model.php | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/composer.json b/composer.json index e2818f5..96ce4e0 100644 --- a/composer.json +++ b/composer.json @@ -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", diff --git a/src/Models/Model.php b/src/Models/Model.php index 4fdcf0c..95821a1 100644 --- a/src/Models/Model.php +++ b/src/Models/Model.php @@ -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())); } /** @@ -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); @@ -335,7 +337,7 @@ private function mapToModel(string $property, mixed $value): mixed })->toArray(); } - return []; + return null; } /**