TechnicalEloquent performance

Eloquent performanceLesson 22 of 28

Make N+1 Issues Impossible

Turn lazy loading into an error in development.

1 min readIntermediateLesson

Eloquent performance22

The problem

Lazy loading is convenient, so it's easy to forget an eager load and ship an N+1.

The fix

Make lazy loading throw an error during development, so a missing eager load fails loudly.

✕ Instead of this

$customers = Customer::paginate();

{{-- Blade: silently runs a query per row --}}
{{ $customer->salesRep->name }}

✓ Do this

// AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());

The benefit

A forgotten eager load throws an error while you're developing, instead of quietly slowing production.

More detail

The lesson (recorded earlier) does it by hand in a shared base model:

public function getRelationshipFromMethod($method)
{
    $modelName = static::class;
    throw new \LogicException("Attempting to lazy-load relation [$method] on model [$modelName]. Lazy loading relationships is not allowed.");
}

Watch out

  • The author described the hand-made version as experimental. Prefer the built-in method if your Laravel version has it.

Frame from lesson 22

With the base-model override in place and the eager load removed, Ignition throws "Lazy-loading relationships is not allowed (App\Customer::salesRep)".

Key takeaway

Turn lazy loading into an error in development.

Check yourself

Why only turn it on outside production?

Reveal answer

✓ Answer

In production you'd rather have a slow page than a crashed one. The goal is to catch mistakes while developing.