BLOG // May 29, 2021

Prevent Lazy Loading in Laravel

Laravel 8.43 has added an excellent new feature, the "preventLazyLoading" function. A large majority of poor SQL performance in Laravel can be attributed to lazy loading. Queries that you think execute a single query may execute thousands.

As discussed, a new feature in Laravel allows you to throw an exception whenever lazy loading occurs. This is obviously only used in development and/or testing environments.

use Illuminate\Database\Eloquent\Model;
[..]
Model::preventLazyLoading(app()->environment('local'));

The snippet of code above enables the feature in the "local" app environment. You could also do this to enable it in all environments except production:

Model::preventLazyLoading(!app()->isProduction());

In my projects I add this to my app/Providers/AppServiceProvider.php boot function, here is an example of the whole file:

<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        //
    }

    public function boot()
    {
        Model::preventLazyLoading(app()->environment('local'));
    }
}

Comments

Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.