Guides · SaaS
Laravel N+1 queries: how to find them and fix them with eager loading.
What the N+1 query problem is, how to spot it in Laravel with Debugbar or Telescope, fixing it with with(), withCount and lazy loading prevention.
Key takeaways
- N+1 means one query to fetch a list, then one extra query per item for a relation.
- Fix it with eager loading:
Post::with('author')->get(). - Turn on
Model::preventLazyLoading()in development so mistakes throw errors. - Always measure. Not every extra query matters, but a table of 100 rows can easily run 101 queries.
What the problem looks like
$posts = Post::all(); // 1 query
foreach ($posts as $post) {
echo $post->author->name; // 1 query per post
}
For 100 posts that is 101 queries. Each is quick, so it looks fine on a small local database, then slows down in production as data grows.
Fix 1: eager loading
$posts = Post::with('author')->get(); // 2 queries total
Laravel runs one query for posts and one for all needed authors, then matches them in memory. Load several relations with an array, and nested ones with dot notation:
Post::with(['author', 'comments.user'])->get();
Fix 2: select only what you need
Post::with('author:id,name')->select('id', 'title', 'author_id')->get();
Remember to include the foreign key, or the relation cannot be matched.
Fix 3: count and sum without loading rows
If you only need a number, do not load the whole relation:
$posts = Post::withCount('comments')->get();
// $post->comments_count
withSum, withAvg and withExists follow the same idea.
Finding N+1 problems
- Laravel Debugbar shows the number and duplicates of queries per page, in development.
- Laravel Telescope records queries across requests.
- Query log:
DB::enableQueryLog(); ... DB::getQueryLog(); - Prevention: in
AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());
With this, accessing a relation that was not eager-loaded throws an exception during development, so you notice at once. In production it is better not to throw.
Where it hides
- Blade loops calling
$item->category->name. - Admin tables. Columns that show related data trigger one query per row. Admin panels need eager loading too. See Filament pros and cons.
- API resources that access relations.
- Accessors that run a query inside a loop.
Beyond eager loading
Once N+1 is gone, remaining slowness usually comes from missing indexes, loading too many rows (use pagination or chunking), or heavy aggregates that should be cached or computed in the database.
- Add indexes on columns used in
where,joinandorder by. - Paginate lists instead of
get()on large tables. - Use
chunk()orlazy()for large batch jobs.
Frequently asked questions
Is eager loading always better?
No. Loading relations you never use wastes memory and time. Load what the screen needs.
Does with() make a single query?
It makes one extra query per relation, not per row. That is the point.
Should I use joins instead?
Joins can be faster for some reports, but eager loading keeps Eloquent models and is simpler for most pages.
Fast pages start with sane queries. See a project where speed mattered.
See the coaching site