On May 25th, 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:

  <?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:

Spread the word!

Leave a Reply

Your email address will not be published. Required fields are marked *