DEV Community

Cover image for Understanding and Fixing the N+1 Query Problem in Laravel
Abiodun Paul Ogunnaike
Abiodun Paul Ogunnaike

Posted on

Understanding and Fixing the N+1 Query Problem in Laravel

If you’ve ever built a Laravel app that felt fast locally but slow in production, there’s a good chance you’ve encountered the N+1 query problem.

It’s one of the most common performance issues in backend development and many developers don’t realize it’s happening.

What is the N+1 Query Problem?

The N+1 problem occurs when:

  • You run 1 query to fetch data
  • Then N additional queries to fetch related data
$users = User::all();

foreach ($users as $user) {
    echo $user->posts;
}
Enter fullscreen mode Exit fullscreen mode

If you have 10 users, Laravel executes:

  • 1 query for users
  • 10 queries for posts

Total: 11 queries

Why This is Dangerous

At small scale, it looks harmless.

At scale:

  • 100 users = 101 queries
  • 1000 users = 1001 queries

This leads to:

  • Slow response times
  • High database load
  • Poor user experience

The Solution: Eager Loading

Laravel provides a simple fix using with():

$users = User::with('posts')->get();
Enter fullscreen mode Exit fullscreen mode

Now Laravel executes:

  • 1 query for users
  • 1 query for posts

Total: 2 queries

Going Deeper: Nested Relationships

The problem becomes worse with nested relationships:

$users = User::all();

foreach ($users as $user) {
    foreach ($user->posts as $post) {
        echo $post->comments;
    }
}
Enter fullscreen mode Exit fullscreen mode

The Fix:

$users = User::with('posts.comments')->get();
Enter fullscreen mode Exit fullscreen mode

Quick Tips

  • Always inspect queries using Laravel Debugbar
  • Be cautious with API resources and transformers
  • Use eager loading by default when returning relationships

Conclusion

The N+1 query problem is easy to miss—but expensive to ignore.

If you’re serious about building scalable Laravel applications, mastering this concept is essential.

Top comments (0)