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.
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:
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 ServiceProvider11 {12 /**13 * Register any application services.14 *15 * @return void16 */17 public function register()18 {19 //20 }21 22 /**23 * Bootstrap any application services.24 *25 * @return void26 */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:
Written by
Writing and maintaining @LaravelMagazine. Host of "The Laravel Magazine Podcast". Pronouns: vi/vim.
Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.