Laravel - Relationships - Preventing Lazy Loading

As previously discussed, eager loading relationships can often provide significant performance benefits to your application. Therefore, if you would like, you may instruct Laravel to always prevent the lazy loading of relationships. To accomplish this, you may invoke the preventLazyLoading method offered by the base Eloquent model class. Typically, you should call this method within the boot method of your application's AppServiceProvider class.

The preventLazyLoading method accepts an optional boolean argument that indicates if lazy loading should be prevented. For example, you may wish to only disable lazy loading in non-production environments so that your production environment will continue to function normally even if a lazy loaded relationship is accidentally present in production code:

    
    use Illuminate\Database\Eloquent\Model;
    
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Model::preventLazyLoading(! $this->app->isProduction());
    }
	

After preventing lazy loading, Eloquent will throw a Illuminate\Database\LazyLoadingViolationException exception when your application attempts to lazy load any Eloquent relationship.

You may customize the behavior of lazy loading violations using the handleLazyLoadingViolationsUsing method. For example, using this method, you may instruct lazy loading violations to only be logged instead of interrupting the application's execution with exceptions:

    
    Model::handleLazyLoadingViolationUsing(function ($model, $relation) {
        $class = get_class($model);
    
        info("Attempted to lazy load [{$relation}] on model [{$class}].");
    });