Skip to content

Commit

Permalink
Load relations before attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
Tofandel committed Oct 20, 2024
1 parent b9b0c88 commit e7b5ce0
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/Normalizers/Normalized/NormalizedModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)) {
Expand All @@ -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();
}

Expand All @@ -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)) ||
Expand Down

0 comments on commit e7b5ce0

Please sign in to comment.