Laravel
Laravel

What is the N+1 query problem and how do you solve it in Eloquent?

December 3, 2025

The N+1 query problem occurs when fetching a collection of parent models (1 query) triggers lazy-loading of relationships for each item (N additional queries), causing severe performance degradation in loops. Eloquent solves this through eager loading with with(), reducing queries from N+1 to typically 2 regardless of collection size.

Step 1:- Identify the Problem (Lazy Loading)

Code

// N+1 PROBLEM: 1 + N queries (disaster at scale)
$users = User::all(); // 1 query
foreach ($users as $user) {
    echo $user->posts->count(); // N queries! One per user
}
      

Step 2:-Apply Eager Loading with with()

Code

// SOLUTION: 2 queries total (scales perfectly)
$users = User::with('posts')->get(); // 1 query users + 1 query all posts
foreach ($users as $user) {
    echo $user->posts->count(); // 0 queries - pre-loaded!
}
      

Step 3:-Eager Load Multiple/Nested Relationships

Code

// Multiple relationships
$users = User::with(['posts', 'profile', 'roles'])->get(); // 4 queries total

// Nested (posts + each post's comments)
$users = User::with('posts.comments')->get(); // Users + Posts + Comments (3 queries)

// Constrained eager loading
$users = User::with(['posts' => function ($query) {
    $query->where('published', true)->latest();
}])->get();
      

Step 4:-Lazy Eager Loading (Existing Collections)

Code

// Already have $users collection? Load later:
$users = User::all(); // 1 query
$users->load('posts'); // 1 more query - now eager loaded!
foreach ($users as $user) {
    echo $user->posts->count(); // 0 queries
}
      

Stpe 5:-Optimize with withCount() (No Full Relation Needed)

Code

// Just need COUNT? Avoid loading full relation:
$users = User::withCount('posts')->get();
foreach ($users as $user) {
    echo $user->posts_count; // 0 queries - just integer!
}
      
Hire Now!

Need Help with Laravel Development ?

Ready to leverage the power of conversational AI? Start your project with Zignuts expert AI developers.
bg-image
download-image
Company Deck
PDF, 3MB
© 2026 Zignuts Technolab. All Rights Reserved.
branch imagesbranch imagesbranch imagesbranch imagesbranch imagesbranch images