Laravel Eloquent: how do I fix the N+1 query problem?
poze 3 months ago363 gadeen
6
My blog index page runs 101 queries for 100 posts because each post accesses $post->author->name. How do I reduce that?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
poze 3 months ago
Grace Deroy 1.9k
1 Repons
7
✓✓ Repons yo aksepte
Eager load the relationship with with(). That's 2 queries instead of 101:
$posts = Post::with('author')->latest()->paginate(20);
Nested and constrained relations work too:
Post::with(['author:id,name', 'comments' => fn ($q) => $q->latest()->limit(3)])->get();
To catch this automatically in development, add this to AppServiceProvider::boot():
Model::preventLazyLoading(! app()->isProduction());
Lazy loading then throws an exception, so N+1s get fixed before they reach production. Laravel Debugbar or Telescope show the query count per page.
Konekte pou di lòt moun si li te mache.
answered 3 months ago
Nadège Paul 1.5k
Sign in and verify your email to post an answer.