Disable lazy loading in Laravel with preventLazyLoading() method
Taylor Otwell tweeted about this new feature available in Laravel 8.43.0 that disables lazy loading your Eloquent models, avoiding the N+1 problem.
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>Today's Laravel 8.43.0 release includes support for disabling lazy loading. π ββοΈhttps://t.co/Vs63bumUx1
β Taylor Otwell πͺ (@taylorotwell) May 25, 2021
In addition, it supports marking jobs as failed immediately on timeout. π₯https://t.co/7lAvc8jhi9
Before this feature to be released, when trying to avoid the N+1 problem and avoid lazy loading on your Eloquent model, you would probably use ->with() helper so you will only query the database for the specified fields, once. That is convenient and itβs working but itβs very easy to forget using ->with() on each Eloquent query you write or using this method it becomes complicated working with deep nested Eloquent queries.
Laravel 8.43.0 introduces a new helper method that allows you to disable lazy loading entirely using Model::preventLazyLoading(). To disable lazy loading, in your AppServiceProvider.php, inside the boot() method you refer to this new helper method doing so:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Model::preventLazyLoading();
}
}
If you explicitly disabled lazy loading and you are trying to lazy load a model, a LazyLoadingViolationException will be thrown. To avoid showing the exception on a production server, you have to specify that in the boot() function like so:
Model::preventLazyLoading(! app()->isProduction());
Now, the exception will only be thrown if the app is in a development enviroment.
Mohamed covers more on this topic in this video: