Fix the N+1 Query Problem in Laravel: Find It, Fix It, Test It
The N+1 query problem is one of the most common reasons a Laravel page is slow, and it hides well. The page works, the code looks tidy, and the problem only shows up when the table grows. This guide explains what it is, how to see it, and the four tools Laravel gives you to fix it.
What this article is, and is not
This is a technique guide. The code is standard Laravel and the query counts are what you get from the example models below. I am not quoting timing figures, because they depend entirely on your data and hardware. The examples use a simple blog with posts, authors and comments, so you can try each step on your own models.
What N+1 means
Suppose a blog page lists posts and shows each author's name:
$posts = Post::latest()->take(20)->get(); // 1 query
foreach ($posts as $post) {
echo $post->author->name; // 1 query per post
}
Accessing $post->author for the first time loads the relationship from the database. With 20 posts that is 1 query for the posts plus 20 for the authors: 21 queries. With 200 posts it is 201. The count grows with the data, which is why the page feels fine in development and slow in production.
How to see it
- Laravel Debugbar (a development package) lists every query for the page and flags duplicates.
- Query log: call
DB::enableQueryLog() before the code and dd(DB::getQueryLog()) after. Repeated queries that differ only by an id are the signature.
- Make Laravel complain: add this to
AppServiceProvider::boot() so lazy loading throws an exception outside production:
use Illuminate\Database\Eloquent\Model;
public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction());
}
In production it stays quiet, so a missed case slows a page down rather than breaking it, while your tests and local work fail loudly and tell you where to fix it.
Fix 1: eager load with with()
$posts = Post::with('author')->latest()->take(20)->get();
Now Laravel runs 2 queries: one for the posts and one for all of their authors at once (where id in (...)), and attaches them. Nested relationships use dot syntax: with('author', 'comments.user').
Fix 2: count with withCount()
If you only need a number, do not load the rows at all:
$posts = Post::withCount('comments')->get();
// each post now has $post->comments_count
This adds a subquery to the same statement. Looping and calling $post->comments->count() would load every comment just to count it.
Fix 3: constrain what you eager load
$posts = Post::with(['comments' => fn ($q) => $q->where('approved', true)->latest()->limit(3)])->get();
Be careful with limit inside an eager load: it limits the whole eager query, not each parent. To get "the latest 3 comments per post" you need a different approach, such as a window function or a query per post you accept knowingly. Selecting columns is allowed, but always include the key that links the relationship, for example with('author:id,name').
Fix 4: load later with load()
When the models already exist, for example from route model binding, use $post->load('comments'), or loadMissing() to skip relationships that are already loaded.
Check the fix, do not assume it
A feature test can assert the number of queries, so a future change cannot quietly bring the problem back:
DB::enableQueryLog();
$this->get('/posts')->assertOk();
$this->assertLessThanOrEqual(5, count(DB::getQueryLog()));
Common mistakes
- Eager loading a relationship the view never uses. It adds a query for nothing.
- Calling a relationship as a method (
$post->comments()->count()) inside a loop. That runs a query every time and ignores eager loading.
- Using
whereHas to filter and expecting it to eager load. It filters only. Add with() as well.
- Treating fewer queries as always better. One huge join that returns far more data can be slower than a few small queries.
Summary
Turn on preventLazyLoading outside production, use with() for rows you display and withCount() for numbers, and add a query-count assertion to the tests for your busiest pages.