Find N+1 problems instantly by disabling lazy loading

Tutorials

May 21st, 2021

strict-model-lazy-loading-featured.png

In the next release of Laravel 8, you can strictly disable lazy loading entirely, resulting in an exception:

Preventing lazy loading in development can help you catch N+1 bugs earlier on in the development process. The Laravel ecosystem has various tools to identify N+1 queries. However, this approach brings the issue front-and-center by throwing an exception.

Demo

Let’s walk through this feature real quick by spinning up a development version of the framework 8.x branch since this feature is not out yet at the time of writing. Once released, you will have this feature without switching to the latest 8.x branch.

Setup

First, create a new application:

1laravel new strict-lazy-demo

Next, we’ll update the laravel/framework version in composer.json to make sure we have this feature (if you’re trying it out before the next release) by adjusting the version to 8.x-dev:

1{
2 "require": {
3 "laravel/framework": "8.x-dev"
4 }
5}

Next, run composer update to make sure you get the latest version of the code for this branch:

1composer update laravel/framework

At this point, you should set up your preferred database. I like running a local MySQL instance using Laravel’s defaults of using the root user without a password. I find it convenient to use the default .env values locally to get started quickly without any configuration.

1mysql -uroot -e"create database strict_lazy_demo"

Once you configure your database of choice, make sure you can migrate:

1php artisan migrate:fresh

Demo Data

We’ll create a Post model and define a one-to-many relationship from the User model to demonstrate this feature. We’ll start by creating the Post model and accompanying files:

1# Create a model with migration and factory
2php artisan make:model -mf Post

First, let’s define our Post migration and factory configuration:

1// Your filename will differ based on when you create the file.
2// 2021_05_21_000013_create_posts_table.php
3
4Schema::create('posts', function (Blueprint $table) {
5 $table->id();
6 $table->foreignIdFor(\App\Models\User::class);
7 $table->string('title');
8 $table->longText('body');
9 $table->timestamps();
10});

Next, define your PostFactory definition method based on the above schema:

1/**
2 * Define the model's default state.
3 *
4 * @return array
5 */
6public function definition()
7{
8 return [
9 'user_id' => \App\Models\User::factory(),
10 'title' => $this->faker->sentence(),
11 'body' => implode("\n\n", $this->faker->paragraphs(rand(2,5))),
12 ];
13}

Finally, open up the DatabaseSeeder file and add the following in the run() method:

1/**
2 * Seed the application's database.
3 *
4 * @return void
5 */
6public function run()
7{
8 \App\Models\User::factory()
9 ->has(\App\Models\Post::factory()->count(3))
10 ->create()
11 ;
12}

Associating Models and Prevent Lazy Loading

Now that we have the migration, seeder, and model created, we are ready to associate a User with the Post model to demo this feature.

Add the following method to the User model to give the user an association with Posts:

1// app/Models/User.php
2/**
3 * @return \Illuminate\Database\Eloquent\Relations\HasMany
4 */
5public function posts()
6{
7 return $this->hasMany(Post::class);
8}

With that in place, we can migrate and seed the database:

1php artisan migrate:fresh --seed

If all went well, we should see something like the following in the console:

We can now using tinker to inspect our seeded data and relationship:

1php artisan tinker
2
3>>> $user = User::first()
4=> App\Models\User {#4091
5 id: 1,
6 name: "Nedra Hayes",
7 email: "bruen.marc@example.com",
8 email_verified_at: "2021-05-21 00:35:59",
9 created_at: "2021-05-21 00:35:59",
10 updated_at: "2021-05-21 00:35:59",
11 }
12>>> $user->posts
13=> Illuminate\Database\Eloquent\Collection {#3686
14 all: [
15 App\Models\Post {#3369
16 id: 1,
17...

The $user->posts property actually calls the database, thus is "lazy" but is not optimized. The convenience of lazy-loading is nice, but it can come with heavy performance burdens in the long-term.

Disabling Lazy Loading

Now that we have the models set up, we can disable lazy loading across our application. You’d likely want to only disable in non-production environments, which is easy to achieve! Open up the AppServiceProvider class and add the following to the boot() method:

1// app/Providers/AppServiceProvider.php
2
3public function boot()
4{
5 Model::preventLazyLoading(! app()->isProduction());
6}

If you run a php artisan tinker session again, this time you should get an exception for a lazy loading violation:

1php artisan tinker
2
3>>> $user = \App\Models\User::first()
4=> App\Models\User {#3685
5 id: 1,
6 name: "Nedra Hayes",
7 email: "bruen.marc@example.com",
8 email_verified_at: "2021-05-21 00:35:59",
9 #password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
10 #remember_token: "jHSxFGKOdw",
11 created_at: "2021-05-21 00:35:59",
12 updated_at: "2021-05-21 00:35:59",
13 }
14>>> $user->posts
15Illuminate\Database\LazyLoadingViolationException with message
16'Attempted to lazy load [posts] on model [App\Models\User] but lazy loading is disabled.'

If you want to visualize what happens if you use lazy loading in a view file, modify the default route as follows:

1Route::get('/', function () {
2 return view('welcome', [
3 'user' => \App\Models\User::first()
4 ]);
5});

Next, add the following somewhere in the welcome.blade.php file:

1<h2>Posts</h2>
2@foreach($user->posts as $post)
3 <h3>{{ $post->title }}</h3>
4 <p>
5 {{ $post->body }}
6 </p>
7@endforeach

If you load up your application through Valet or artisan serve, you should see something like the following error page:

Though you’ll get exceptions during development, accidentally deploying code that triggers lazy-loading will continue to work as long as you set environment checking correctly in the service provider.

Learn More

You can learn how this feature was implemented: 8.x Add eloquent strict loading mode - Pull Request #37363. Huge thanks to Mohamed Said, contributors, and of course Taylor Otwell for adding the polish to disable lazy loading conditionally.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.