You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
HasAttributes::handleLazyLoadingViolation shouldn't throw LazyLoadingViolationException if model instance was created in memory, and not fetched from the database. It's impossible to eager load relations for a model that doesn't exist yet. Throwing an exception in this scenario doesn't prevent unnecessary database queries and requires manual bypassing.
I solved it by adding the following to AppServiceProvider:
Model::handleLazyLoadingViolationUsing(
static function (Model $model, string $relation) {
// It's fine that you didn't eager load relations for a new model as it wouldn't make sense
if (!$model->exists || $model->wasRecentlyCreated) {
return;
}
throw new LazyLoadingViolationException($model, $relation);
}
);
I believe this condition should be built into HasAttributes::handleLazyLoadingViolation.
!$model->exists isn't enough in the second case because relation wasn't initialized before saving the model.
Why I bumped into this issue:
I expect the question "why do you use relations like that?" so let me answer upfront. I'm trying to use a DDD approach where the operations are split into stages (simplified):
Load models from database
Modify models – make new children instances and push them to relation collection (or not, depends on request data)
Persist models to database - iterate over relation collection items, set the parent ID and save to database
The text was updated successfully, but these errors were encountered:
Description:
framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Lines 517 to 524 in 91c60ea
HasAttributes::handleLazyLoadingViolation
shouldn't throwLazyLoadingViolationException
if model instance was created in memory, and not fetched from the database. It's impossible to eager load relations for a model that doesn't exist yet. Throwing an exception in this scenario doesn't prevent unnecessary database queries and requires manual bypassing.I solved it by adding the following to
AppServiceProvider
:I believe this condition should be built into
HasAttributes::handleLazyLoadingViolation
.Steps To Reproduce:
Fixed by checking
!$model->exists
:Fixed by checking
$model->wasRecentlyCreated
:!$model->exists
isn't enough in the second case because relation wasn't initialized before saving the model.Why I bumped into this issue:
I expect the question "why do you use relations like that?" so let me answer upfront. I'm trying to use a DDD approach where the operations are split into stages (simplified):
The text was updated successfully, but these errors were encountered: