From e7b5ce02e14cf081707db9166b800f904207e41f Mon Sep 17 00:00:00 2001 From: Tofandel Date: Sun, 20 Oct 2024 10:38:33 +0200 Subject: [PATCH] Load relations before attributes --- src/Normalizers/Normalized/NormalizedModel.php | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/Normalizers/Normalized/NormalizedModel.php b/src/Normalizers/Normalized/NormalizedModel.php index a992e7f8..2443719f 100644 --- a/src/Normalizers/Normalized/NormalizedModel.php +++ b/src/Normalizers/Normalized/NormalizedModel.php @@ -2,6 +2,7 @@ namespace Spatie\LaravelData\Normalizers\Normalized; +use Illuminate\Database\Eloquent\MissingAttributeException; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; use ReflectionProperty; @@ -38,10 +39,6 @@ public function getProperty(string $name, DataProperty $dataProperty): mixed protected function fetchNewProperty(string $name, DataProperty $dataProperty): mixed { - if ($this->hasModelAttribute($name)) { - return $this->properties[$name] = $this->model->getAttribute($name); - } - $camelName = Str::camel($name); if ($dataProperty->attributes->contains(fn (object $attribute) => $attribute::class === LoadRelation::class)) { @@ -59,6 +56,14 @@ protected function fetchNewProperty(string $name, DataProperty $dataProperty): m return $this->properties[$name] = $this->model->getRelation($camelName); } + if (!$this->model->isRelation($name) && !$this->model->isRelation($camelName)) { + try { + return $this->properties[$name] = $this->model->getAttribute($name); + } catch (MissingAttributeException) { + // Fallback if missing Attribute + } + } + return $this->properties[$name] = UnknownProperty::create(); } @@ -69,15 +74,12 @@ protected function hasModelAttribute(string $name): bool } // TODO: remove this once we stop supporting Laravel 10 - if (! isset($this->attributesProperty)) { $this->attributesProperty = new ReflectionProperty($this->model, 'attributes'); - $this->attributesProperty->setAccessible(true); } if (! isset($this->castsProperty)) { $this->castsProperty = new ReflectionProperty($this->model, 'casts'); - $this->castsProperty->setAccessible(true); } return array_key_exists($name, $this->attributesProperty->getValue($this->model)) ||