Skip to content

Commit

Permalink
Fix 792
Browse files Browse the repository at this point in the history
  • Loading branch information
rubenvanassche committed Jun 25, 2024
1 parent d2780f2 commit b7e10d3
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Normalizers/Normalized/NormalizedModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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])) {
Expand Down
5 changes: 5 additions & 0 deletions tests/Fakes/Models/FakeModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
32 changes: 32 additions & 0 deletions tests/Normalizers/ModelNormalizerTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use Illuminate\Database\LazyLoadingViolationException;
use Illuminate\Support\Facades\DB;
use Spatie\LaravelData\Attributes\DataCollectionOf;
use Spatie\LaravelData\Attributes\LoadRelation;
Expand Down Expand Up @@ -197,3 +198,34 @@

expect($data)->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);
});

0 comments on commit b7e10d3

Please sign in to comment.