What is the N+1 query problem and how does eager loading solve it in Laravel?
The N+1 problem occurs when you load a collection of records and then access a relationship on each one individually, causing one extra query per record:
// ❌ N+1 — 1 query for posts + 1 query per post for its author
$posts = Post::all(); // 1 query
foreach ($posts as $post) {
echo $post->author->name; // 1 query × N posts = N queries
}
// Total: 1 + N queries
Eager loading with with() resolves the relationship in just 2 queries total:
// ✅ Eager loading — 2 queries total regardless of record count
$posts = Post::with('author')->get();
foreach ($posts as $post) {
echo $post->author->name; // no extra query
}
$posts = Post::with(['author', 'tags', 'comments.user'])->get();
$posts = Post::with([
'comments' => fn ($q) => $q->where('approved', true)->latest()->limit(5),
])->get();
// AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());
All Comments