Skip to content
OpenCloseEsc
Tips
  • Laravel
  • eloquent
  • performance

Turn lazy loading into an exception in development

Model::preventLazyLoading() makes every accidental N+1 throw while you develop, so missing with() calls are found before they reach production.

1 min read

An N+1 is silent: the page works, it is just slow once the list grows. One line in AppServiceProvider::boot() makes the relation access throw instead.

use Illuminate\Database\Eloquent\Model;
 
public function boot(): void
{
    Model::preventLazyLoading(! $this->app->isProduction());
}

Now $order->customer->name inside a loop over orders throws LazyLoadingViolationException with the model and relation name, and the fix is Order::with('customer'). Production keeps the old behaviour, so a missed case degrades to slow rather than broken.

Model::shouldBeStrict() goes further: it also throws on access to attributes that were not selected and on filling guarded attributes.