diff --git a/src/Normalizers/Normalized/NormalizedModel.php b/src/Normalizers/Normalized/NormalizedModel.php index ddd1a5fa..9d1a7c70 100644 --- a/src/Normalizers/Normalized/NormalizedModel.php +++ b/src/Normalizers/Normalized/NormalizedModel.php @@ -34,7 +34,7 @@ public function getProperty(string $name, DataProperty $dataProperty): mixed protected function initialize(Model $model): void { - $this->properties = $model->withoutRelations()->toArray(); + $this->properties = $model->attributesToArray(); foreach ($model->getDates() as $key) { if (isset($this->properties[$key])) { diff --git a/tests/Fakes/Models/FakeModel.php b/tests/Fakes/Models/FakeModel.php index 78523bd6..b1bc83b7 100644 --- a/tests/Fakes/Models/FakeModel.php +++ b/tests/Fakes/Models/FakeModel.php @@ -47,6 +47,11 @@ public function performanceHeavyAccessor(): Attribute return Attribute::get(fn () => throw new Exception('This accessor should not be called')); } + public function getAccessorUsingRelationAttribute(): string + { + return $this->fakeNestedModels->first()->string; + } + protected static function newFactory() { return FakeModelFactory::new(); diff --git a/tests/Normalizers/ModelNormalizerTest.php b/tests/Normalizers/ModelNormalizerTest.php index d3de5f4d..04bc3601 100644 --- a/tests/Normalizers/ModelNormalizerTest.php +++ b/tests/Normalizers/ModelNormalizerTest.php @@ -1,5 +1,6 @@ oldAccessor->toEqual($model->old_accessor); }); + +it('can create a data property for a model attribute which fetches a relation that is loaded and it will not trigger a lazy loading exception', function () { + $dataClass = new class ('') extends Data { + public function __construct(public string $accessor_using_relation) + { + } + }; + + $model = FakeModel::factory()->create(); + FakeNestedModel::factory()->for($model)->create(); + + $freshModel = FakeModel::query()->first(); + + $freshModel->preventsLazyLoading = true; + + expect(function () use ($dataClass, $freshModel) { + $freshModel->append('accessorUsingRelation'); + + $dataClass::from($freshModel); + })->toThrow(LazyLoadingViolationException::class); + + $freshModel = $freshModel + ->load('fakeNestedModels') + ->append('accessorUsingRelation'); + + $data = $dataClass::from($freshModel); + + expect($freshModel) + ->accessor_using_relation + ->toEqual($data->accessor_using_relation); +});