November 19th, 2021

laravel-caching.jpeg

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.

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:

1<?php
2 
3 namespace App\Providers;
4 
5 use Illuminate\Support\ServiceProvider;
6 use Illuminate\Database\Eloquent\Builder;
7 use Illuminate\Database\Eloquent\Model;
8 
9 
10 class AppServiceProvider extends ServiceProvider
11 {
12 /**
13 * Register any application services.
14 *
15 * @return void
16 */
17 public function register()
18 {
19 //
20 }
21 
22 /**
23 * Bootstrap any application services.
24 *
25 * @return void
26 */
27 public function boot()
28 {
29 Model::preventLazyLoading();
30 }
31 }

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:

1Model::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:

Follow @LaravelMagazine on Twitter →
Marian Pop

I’m a Full-Stack Developer based in Transylvania. I use Laravel daily whether it’s for work or my personal projects.

Newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox every Friday!

We'll never share your email address and you can opt out at any time.