It's a good practice to disable lazy-loading in your Laravel code when running in development (or testing) mode. This will help you avoid N+1 problems.

You can easily do this by adding the following to your AppServiceProvider::boot function:

<?php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Model::preventLazyLoading(App::environment('local', 'testing'));
    }

    public function register()
    {
    }
}

There's one drawback though, it's all or nothing. When you are working with an existing codebase and you want to gradually fix the issues, you might need to (temporarily) disable the check for certain models and / or relations.

To do so, you can register a closure using Model::handleLazyLoadingViolationUsing to customize the check

<?php

namespace App\Providers;

use App\Domains\User\CompanyUser;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\LazyLoadingViolationException;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\App;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Model::handleLazyLoadingViolationUsing(function (Model $model, string $relation): void {
            if ($model instanceof CompanyUser) {
                if ($relation === 'offices') {
                    return;
                }
            }
            throw new LazyLoadingViolationException($model, $relation);
        });

        Model::preventLazyLoading(App::environment('local', 'testing'));
    }

    public function register()
    {
    }
}

In the above example, we no longer throw the lazy-loading error when loading the offices relation on the model CompanyUser.

Related Posts

  • Optimising large whereIn queries in Laravel
  • Laravel Service Provider in Simple English
  • Using macros with Laravel
  • Testing for equal json strings in Laravel tests
  • The giveConfig function in Laravel