Laravel Eloquent: how do I fix the N+1 query problem?
asked 3 months ago364 viewsen
6
My blog index page runs 101 queries for 100 posts because each post accesses $post->author->name. How do I reduce that?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
asked 3 months ago
Grace Deroy 1.9k
1 Answer
7
✓✓ Accepted answer
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.
Sign in to tell others whether this worked.
answered 3 months ago
Nadège Paul 1.5k
Sign in and verify your email to post an answer.