Diagnosing and fixing an Eloquent N+1 query
How to spot N+1 queries in Laravel, fix them with eager loading, withCount() and constrained loads, and make Laravel throw an exception the next time one slips in.
On this page
An N+1 query happens when you load a list of N records with one query, then trigger one more query for each record as you touch a relationship. Fifty posts become 51 queries. It is the most common performance problem in Eloquent code because the code looks innocent:
$posts = Post::latest()->take(50)->get(); // 1 query
foreach ($posts as $post) {
echo $post->author->name; // +1 query per post
}
Spot it
- Laravel Debugbar or Telescope show the query count per request. Repeated identical queries with different IDs are the signature.
- In tests, count queries:
DB::enableQueryLog(); ...; $this->assertLessThan(10, count(DB::getQueryLog())); - Best of all, make Laravel refuse lazy loading outside production, in
AppServiceProvider::boot():
use Illuminate\Database\Eloquent\Model;
Model::preventLazyLoading(! app()->isProduction());
Now the loop above throws LazyLoadingViolationException in development and tests, naming the model and relationship.
Fix it with eager loading
$posts = Post::with('author')->latest()->take(50)->get(); // 2 queries in total
with() loads all authors in one WHERE id IN (...) query. Nested and multiple relations work too:
Post::with(['author', 'comments.user', 'tags'])->get();
Already have the collection (for example from a paginator)? Use $posts->load('author'), or loadMissing() to skip relations that are already loaded.
Counts and sums without loading rows
Showing “12 comments” does not need the comments:
$posts = Post::withCount('comments')->withSum('orders', 'total')->get();
$post->comments_count;
$post->orders_sum_total;
Load only what you need
Post::with([
'comments' => fn ($q) => $q->latest()->limit(3),
'author:id,name',
])->get();
Selecting columns on a relation must include the keys Eloquent needs to match records (id here). Since Laravel 11, limit() inside an eager-load constraint applies per parent, not globally.
Hidden N+1s
- Accessors and
$appendsthat touch a relationship run for every model when you serialize to JSON. - API resources that call
$this->authorwithoutwhenLoaded('author'). - Blade components in a loop that query on their own.
- Policies that load relations in
@canchecks inside a loop.
preventLazyLoading() catches all of these, which is why it is worth turning on before you go hunting by hand.
When eager loading is not the answer
For large reports, a single query with a join or a database view can beat loading thousands of models. And if the list is huge, combine eager loading with chunking (lazyById()) so you do not trade an N+1 for a memory limit error.