Skip to content

Commit b7e10d3

Browse files
Fix 792
1 parent d2780f2 commit b7e10d3

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

src/Normalizers/Normalized/NormalizedModel.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public function getProperty(string $name, DataProperty $dataProperty): mixed
3434

3535
protected function initialize(Model $model): void
3636
{
37-
$this->properties = $model->withoutRelations()->toArray();
37+
$this->properties = $model->attributesToArray();
3838

3939
foreach ($model->getDates() as $key) {
4040
if (isset($this->properties[$key])) {

tests/Fakes/Models/FakeModel.php

+5
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@ public function performanceHeavyAccessor(): Attribute
4747
return Attribute::get(fn () => throw new Exception('This accessor should not be called'));
4848
}
4949

50+
public function getAccessorUsingRelationAttribute(): string
51+
{
52+
return $this->fakeNestedModels->first()->string;
53+
}
54+
5055
protected static function newFactory()
5156
{
5257
return FakeModelFactory::new();

tests/Normalizers/ModelNormalizerTest.php

+32
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?php
22

3+
use Illuminate\Database\LazyLoadingViolationException;
34
use Illuminate\Support\Facades\DB;
45
use Spatie\LaravelData\Attributes\DataCollectionOf;
56
use Spatie\LaravelData\Attributes\LoadRelation;
@@ -197,3 +198,34 @@
197198

198199
expect($data)->oldAccessor->toEqual($model->old_accessor);
199200
});
201+
202+
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 () {
203+
$dataClass = new class ('') extends Data {
204+
public function __construct(public string $accessor_using_relation)
205+
{
206+
}
207+
};
208+
209+
$model = FakeModel::factory()->create();
210+
FakeNestedModel::factory()->for($model)->create();
211+
212+
$freshModel = FakeModel::query()->first();
213+
214+
$freshModel->preventsLazyLoading = true;
215+
216+
expect(function () use ($dataClass, $freshModel) {
217+
$freshModel->append('accessorUsingRelation');
218+
219+
$dataClass::from($freshModel);
220+
})->toThrow(LazyLoadingViolationException::class);
221+
222+
$freshModel = $freshModel
223+
->load('fakeNestedModels')
224+
->append('accessorUsingRelation');
225+
226+
$data = $dataClass::from($freshModel);
227+
228+
expect($freshModel)
229+
->accessor_using_relation
230+
->toEqual($data->accessor_using_relation);
231+
});

0 commit comments

Comments
 (0)