Laravel Development
Your Laravel Page Loads 100 Database Queries for 100 Records? Fix the N+1 Query Problem
Your Laravel page may look simple, but behind the scenes it could be executing dozens or hundreds of unnecessary database queries. Learn how the N+1 query problem happens, how to identify it with Laravel Debugbar and query logging, and how to fix it using Eloquent eager loading.
Laravel Development
Your Laravel Page Loads 100 Database Queries for 100 Records? Fix the N+1 Query ProblemA page can look perfectly fine with a few records and become painfully slow in production. One common reason is the N+1 query problem. Learn how to identify it, fix it with eager loading, and prevent it from returning.
The problem: one query becomes hundreds
Imagine you are building a Laravel page that displays 100 blog posts. Each post also displays the name of its author. You load the posts, loop through them, and access the author relationship.
The page works, but Laravel may execute one query to retrieve the posts and another query for each post's author. That means 1 query for the posts plus 100 queries for the authors: 101 queries in total.
This is called the N+1 query problem. It can increase response time, database load, and resource usage as your application grows.
1. Understand the N+1 query problem
Consider a Post model with an author relationship:
class Post extends Model
{
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
}
A controller might retrieve posts like this:
public function index()
{
$posts = Post::latest()->take(100)->get();
return view('posts.index', compact('posts'));
}
Then the Blade template accesses the author for every post:
@foreach ($posts as $post)
<h2>{{ $post->title }}</h2>
<p>Written by {{ $post->author->name }}</p>
@endforeach
Accessing author
inside the loop can trigger a separate relationship query for each post when the relationship has not already been loaded.
2. Fix it with eager loading
Laravel provides eager loading through the
with()
method. It retrieves the related records in a separate, batched query instead of running a query for every post.
public function index()
{
$posts = Post::with('author')
->latest()
->take(100)
->get();
return view('posts.index', compact('posts'));
}
Now Laravel typically runs two queries: one for the posts and one for the authors. The exact number can vary with relationships and additional eager-loaded data, but it no longer needs one author query per post.
3. Eager load multiple relationships
Real applications often display more than an author. A post might also show its category, tags, and comments. You can eager load multiple relationships together.
$posts = Post::with([
'author',
'category',
'tags',
'comments',
])->latest()->get();
You can also eager load nested relationships:
$posts = Post::with([
'comments.user',
])->get();
This is useful when your page displays each comment together with the user who wrote it.
4. Load only the columns you need
Eager loading reduces query count, but retrieving unnecessary columns can still waste memory and database resources. You can select specific columns when loading relationships.
$posts = Post::query()
->select(['id', 'title', 'user_id'])
->with('author:id,name')
->latest()
->get();
Keep the relationship keys needed by Eloquent. For a
belongsTo
relationship, the parent query needs its foreign key, and the related query needs the related model's key.
5. Find N+1 queries during development
Do not wait for users to report slow pages. Inspect database queries while developing and testing. Laravel provides useful tools for this.
Use Laravel Debugbar
Laravel Debugbar can show the queries executed during a request, their duration, and repeated query patterns. It is useful during local development. Do not expose debugging tools in production.
Use query logging temporarily
use Illuminate\Support\Facades\DB;
DB::listen(function ($query) {
logger()->debug('Database query', [
'sql' => $query->sql,
'time_ms' => $query->time,
]);
});
Add this temporarily in a suitable local development location. Avoid logging sensitive bindings or enabling verbose query logging indiscriminately in production.
6. Prevent lazy loading mistakes
Laravel can help you catch accidental lazy loading during development. In your
AppServiceProvider,
you can enable lazy-loading prevention outside production.
use Illuminate\Database\Eloquent\Model;
public function boot(): void
{
Model::preventLazyLoading(! app()->isProduction());
}
When code attempts to lazy load a relationship that was not loaded, Laravel can raise an exception in development. This makes accidental N+1 issues easier to detect before deployment.
7. Do not confuse query count with query performance
Eager loading is not a universal fix for every slow database page. A page can execute only a few queries and still be slow because of missing indexes, expensive joins, large result sets, or inefficient filtering.
Use pagination for large collections, add indexes for frequently filtered or joined columns when justified, and inspect slow queries with your database's query analysis tools.
$posts = Post::with('author')
->latest()
->paginate(20);
Final thoughts
The N+1 query problem is easy to miss because the application may work correctly with a small amount of data. As the number of records grows, those repeated queries can become a serious performance bottleneck.
Start by checking relationship access inside loops. Use
with()
to eager load the relationships you need, inspect queries during development, and paginate large result sets.
A faster Laravel application is not always about buying a bigger server. Sometimes, it starts with writing fewer database queries.