Learn how to fix the Laravel N+1 query problem and optimize your queries. Stop performance issues with eager loading in Laravel projects—step-by-step 2026 guide.
Every Laravel developer runs into the N+1 query problem at some point: your application makes a huge number of SQL queries instead of just a few, slowing everything down. The quick fix is to use Eloquent’s eager loading (with) to fetch related data in bulk, not inside a loop. In this post I’ll walk you through spotting, understanding, and fixing the N+1 issue in your Laravel apps, with clean examples and production-tested advice.
If you've built even a medium-sized Laravel project, you've probably been surprised by how fast your database query log explodes. In 2026 projects, where APIs and admin panels can handle tens of thousands of entities, the hidden N+1 bug can silently impact stacks and increase cloud costs. Stopping the laravel n+1 query problem is about mastering your ORM and using Eloquent's features effectively.
What is the Laravel N+1 Query Problem?
The Laravel N+1 query problem happens when Eloquent loads related models inside a loop, causing one query for the parent, then N additional queries for each relation. This often goes unnoticed when you're testing with seed data, but it crushes real-world performance at scale.
For example, loading a list of posts with their authors, but not eager loading the authors, results in one query for the posts and one for each author. This can easily balloon into hundreds or thousands of unnecessary queries, crushing performance and hammering your database.
Internally, Eloquent's lazy loading means that when you access a relation like $post->author inside each iteration, Laravel fires a separate query for each unique author_id found. So, with 500 posts, you could end up executing 501 queries—one for the posts, 500 for the authors—when just two queries would suffice with eager loading.
- 1 query for fetching all posts
- N queries for fetching author for each post
- Easily missed in small data, but a huge problem at scale
UNDER THE HOOD: Why Does N+1 Query Problem Occur in Laravel?
Laravel's Eloquent ORM is built on the principle of intuitively accessing relationships, but this ease of use can obscure what queries are run under the hood. When you access a relationship property on a model (e.g., $post->author), Eloquent detects if the relationship is already loaded. If not, it issues a database query for it. Inside a foreach loop, this means you repeat the lookup for every model, resulting in N additional queries.
Developers often forget that accessing a property doesn't automatically mean it was loaded efficiently. This is especially tricky for new team members or during rapid prototyping. The laravel n+1 query problem doesn't only affect basic relationships but becomes critical with polymorphic and nested relations, too.
How to Fix Laravel N+1 Query Problem with Eager Loading
The easiest and correct way to fix the Laravel N+1 query problem is to use eager loading with with(). This loads all related models in as few queries as possible, outside of the loop. Here’s a real-world example relevant for 2026 projects which may feature multiple relations and deeper data hierarchies.
Imagine a Post model that belongsTo Author:
// The N+1 problem: loads authors inside the loop
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name;
}
// Fix with eager loading:
$posts = Post::with('author')->get();
foreach ($posts as $post) {
echo $post->author->name;
}
Detecting Laravel N+1 Query Problem in Your Project
You might not notice you have a laravel n+1 query problem until your app slows down or your database gets hammered under traffic spikes. Laravel provides powerful ecosystem tools for detection before hitting production.
Laravel Debugbar (https://github.com/barryvdh/laravel-debugbar) overlays a query counter and individual queries on your local development browser. If you see a sudden spike (21 queries for 20 posts), that's a classic N+1 symptom. Laravel Telescope offers even more in-depth tracking, letting you drill into the full query timeline and execution times per request. Regularly profiling your endpoints is critical; even GraphQL APIs and Vue/React SPA endpoints can easily suffer if relationship loading is missed.
- Install Laravel Debugbar: composer require barryvdh/laravel-debugbar --dev
- Watch the Queries tab for repeated queries when iterating.
- Use Telescope for deeper production monitoring.
Typical Eloquent Relationships Driving N+1 Issues
The laravel n+1 query problem is not limited to one relationship type. N+1 problems show up in all types of Eloquent relationships: belongsTo, hasMany, morphMany, and beyond. If you access any relationship inside a loop without eager loading, you might trigger a cascade of N+1 queries.
Common real-world examples, especially as your schema evolves:
- Post::all() with author (belongsTo)
- User::all() with posts (hasMany)
- Order::all() with lineItems (hasMany)
- Comment::all() with commentable (morphTo)
How to Use Eager Loading Correctly in Laravel
To solve the laravel n+1 query problem, always eager-load only what you need, not every relation. Eager loading too many relations can cause memory and performance trouble of its own.
Laravel’s with() method lets you load single, multiple, or even nested relationships for deep hierarchies.
Below are some typical efficient usage patterns. These scale to dozens of thousands of records and nested relations:
// Single relation
$posts = Post::with('author')->get();
// Multiple relations
$posts = Post::with(['author', 'comments'])->get();
// Nested relations
$posts = Post::with(['author.profile', 'comments.user'])->get();
Eager Loading with Conditions and Optimization
Sometimes, you only want to fetch a filtered subset of related data, or limit fields to shrink payload size and RAM usage. Adding constraints inside with() lets you efficiently solve the laravel n+1 query problem and avoid over-fetching.
For example, you may only want 'active' authors or just select a few columns. This sharpens performance and keeps queries small—even when APIs multiply:
// Only load authors with status=active
$posts = Post::with(['author' => function ($query) {
$query->where('status', 'active');
}])->get();
// Only load specific columns from the relation
$posts = Post::with(['author:id,name'])->get();
Lazy Eager Loading vs. Eager Loading in Laravel
Laravel also offers lazy eager loading (the load() method). This is essential when you’ve already retrieved models (perhaps with some global scope or custom filter), and then realize you need to load a relationship. Lazy eager loading still fetches efficiently (one extra query per relation, not per loop iteration), as long as you don’t loop and call the relation repeatedly.
Example:
// Lazy eager load after initial query
$posts = Post::all();
$posts->load('author');
// Beware: if you call $post->author in a loop before calling load(), you reintroduce N+1 problems.
Performance Impact of the Laravel N+1 Query Problem
Fixing the laravel n+1 query problem can make orders of magnitude difference at scale. For instance, an endpoint that loads 500 orders each with 8 line items and customer references will trigger over 1,500 queries unless you properly eager-load. Benchmarking with Xdebug or Blackfire often reveals database queries dominating request time, especially under load.
Cloud platforms like Laravel Vapor or serverless solutions magnify this cost with cold start penalties and per-query latencies. In 2026, with auto-scaling databases and multi-tenant SaaS apps, a hidden N+1 can explode cloud bills and bust SLAs. Always authority-check your production endpoints for hidden query growth as your data grows.
Best Practices to Avoid Laravel N+1 Query Problem
In production apps, I stick to a few habits to avoid N+1 surprises and enforce good team hygiene around Eloquent relationships:
- Always glance at queries on new views with Debugbar or Telescope while developing. - Use with() in controllers, repositories, or queries—not in blade templates, JSX, or similar view layers. Loading data should be in your data-access logic. - Only eager-load the relations you really need for each endpoint or page. Overfetching unrelated tables can kill memory efficiency. - Use select() inside with() for slimmer, faster responses, especially in API-driven Laravel projects. - If you see query-per-row patterns in logs or performance graphs, investigate for forgotten lazy loading before shipping. - Periodically profile queries and their timing on large production-like data sets. - Document required eager loads for critical aggregates (like dashboards) in code comments and code review checklists. - Use Model::withCount() for counts instead of loading all rows (e.g., Post::withCount('comments')). - Write test coverage using tools like laravel-query-detector to catch N+1s in CI before they hit staging.
Common Errors and Troubleshooting N+1 in Laravel
Don’t confuse empty relations with missing eager loading: if relation data is missing, always check your factories, seeders, and fixtures first.
If you mistype the relation name in with(), Laravel will quietly ignore it, meaning the n+1 query problem returns without error. Always use IDE autocomplete or code navigation for correct, defined relation names.
Watch for indirect N+1s on nested relationships—for example, Post -> comments -> user. Even if you eager-load comments, failing to eager-load comments.user creates a second-layer N+1.
Never try to eager-load computed properties or accessors. These aren’t real database columns, and Eloquent eager loading won’t load them from the DB layer.
If you're not seeing the performance boost you'd expect, double-check that relationships are properly configured in your models (i.e., the correct foreign keys and return types).
Advanced Prevention: Static Analysis, Policy, and Team Workflows
In larger teams or critical projects, static analyzers (like Laravel Idea, Larastan, or Psalm with doctrine analysis) can catch missed with()s and highlight slow relationship queries in pull requests. Consider enforcing a CI pipeline gate that checks for excessive queries per route using tools like BeyondCode's laravel-query-detector.
Set clear code review policies: always mention / check for the laravel n+1 query problem in PRs touching Eloquent code. If you use repositories or services, centralize query patterns for consistency (and easier future refactoring). Document known hotspots and model-layer best practices in onboarding docs.
Conclusion: Mastering the Laravel N+1 Query Problem
The Laravel N+1 query problem is easy to trigger and devastating to app performance, but it’s just as easy to fix with eager loading. Once you learn to spot and crush N+1 with tools like Laravel Debugbar, Telescope, and strong programming habits like always adding with() for every needed relationship, you’ll prevent a whole class of bugs from ever making it to production.
The N+1 bug is the single biggest Eloquent mistake I see in code reviews—one that can scale from a trivial local issue on a test DB to cloud-melting downtime in production. By using the techniques above—code review, automated detection, clear best practices, static analysis, and observability—you’ll squash N+1s for good in your 2026 Laravel projects.
Frequently asked questions
How do I solve the Laravel N+1 query problem?
Use Eloquent’s with() method to eager load related data. For example, instead of running Post::all() and then accessing $post->author in a loop (which triggers N+1 queries), use Post::with('author')->get() to load everything in two queries. This applies for any relationship (hasMany, belongsTo, etc).
Why is the N+1 query problem bad in Laravel?
It causes your application to run one query per parent and one query for each relation, quickly racking up hundreds or thousands of slow queries. This both hurts performance and increases database/server costs. The laravel n+1 query problem is among the most common performance bugs in complex apps.
How can I detect N+1 queries in my Laravel app?
Install Laravel Debugbar or Telescope in development, then check the query count during page loads or API requests that fetch multiple models with relations. If you see a query count much higher than the number of parent records, you likely have an N+1 issue. Debugbar shows the repeated queries clearly.
What is the difference between eager loading and lazy loading in Laravel?
Eager loading fetches all needed related models up front in as few queries as possible using with(), while lazy loading loads related data separately for each parent as needed—this is what creates N+1 problems if placed inside loops. Lazy eager loading with load() helps when you need to fetch after retrieving the parents.
Can the N+1 problem happen with nested relationships?
Yes. If you load deep relations (like posts.comments.user) without eager loading all levels with nested with() calls, you risk multiple N+1 layers, causing exponential query growth. Always specify all required nested relations to avoid this issue.
Is this fixed in latest Laravel versions or will it change by 2026?
The laravel n+1 query problem is intrinsic to how ORMs work, and although Laravel continues to improve developer experience (e.g., debug warnings in Telescope, new profiler tools), it will still be possible to trigger N+1s as long as you use relationships. Always use best practices and profile actively.
Originally published at naeemamin.cloud.
Top comments (0)