What is Eager Loading and why is it important in Laravel?

What is Eager Loading and why is it important in Laravel?

What is Eager Loading and why is it important in Laravel?

Question

What is the N+1 query problem and how does eager loading solve it in Laravel?

Answer

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
}

Loading Multiple & Nested Relationships

$posts = Post::with(['author', 'tags', 'comments.user'])->get();

Constrained Eager Loading

$posts = Post::with([
    'comments' => fn ($q) => $q->where('approved', true)->latest()->limit(5),
])->get();

Detecting N+1 in Development

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