Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Delegate lazy loading violation to method #37480

Merged
merged 3 commits into from
May 26, 2021

Conversation

bonroyage
Copy link
Contributor

@bonroyage bonroyage commented May 25, 2021

This PR delegates the throwing of the LazyLoadingViolationException to a new method. This first checks the existence of a static callback for overriding the behaviour in the service provider, if not defined throw the exception as before. The user may override the method on their own models to customise the behaviour for specific models.

This would allow the user to enable the preventLazyLoading flag on all environments while being able to log a message instead of throwing an exception on production environments or in certain other scenarios:

// AppServiceProvider

public function boot()
{
    Model::handleLazyLoadingViolationUsing(function($model, $key) {
        \Log::warning("Lazy loaded relation [{$key}] on model [" . get_class($model) . "].");
    });
}
// A model

protected function handleLazyLoadingViolation($key)
{
    if(app()->isProduction()) {
        \Log::warning("Lazy loaded relation [{$key}] on model [" . get_class($this) . "].");
    } else {
        throw new LazyLoadingViolationException($this, $key);
    }
}

@bonroyage
Copy link
Contributor Author

A possible further enhancement could be allowing this method to return false and preventing the relationship from being loaded without having thrown an exception. In that case the "attribute" would just return null just like the isRelation check does a little earlier and the behaviour is similar to the model events for saving, etc. where a false return value prevents the save() method from being called. I'd be happy to add it to this PR if wanted.

if ($this->preventsLazyLoading && $this->violatedLazyLoading($key) === false) {
    return;
}

bonroyage added 2 commits May 26, 2021 12:16
Adds a way to call `Model::handleLazyLoadingViolationUsing()` from a service provider to add a way to handle violations for all models instead of overriding `violatedLazyLoading` on the models themselves.
@taylorotwell taylorotwell merged commit fd3ab0c into laravel:8.x May 26, 2021
@bonroyage bonroyage deleted the lazy-loading branch May 26, 2021 13:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants