How to Find and Fix N+1 Queries in Laravel

A page that runs fine with ten rows and crawls with ten thousand is often an N+1 problem. It is one of the most common causes of slow Laravel pages, and one of the easiest to fix.

5 min readBy Saad Ali KhanOct 2026
How to Find and Fix N+1 Queries in Laravel

What an N+1 query looks like

You load a list of records with one query, then access a relationship on each one. Each access runs another query, so a list of 100 posts triggers 1 + 100 queries.

$posts = Post::all();               // 1 query

foreach ($posts as $post) {
    echo $post->author->name;        // 1 query per post
}

Fix 1: eager load with with()

Tell Eloquent up front which relationships you need. It loads them in one extra query instead of one per row.

$posts = Post::with('author')->get();   // 2 queries total

Nested relationships work too: with('author.company'). You can also select only the columns you need, for example with('author:id,name'), making sure to include the key columns Eloquent needs to match rows.

Fix 2: use withCount for totals

If you only need a count, do not load every related row just to count it in PHP.

$posts = Post::withCount('comments')->get();
// $post->comments_count

Fix 3: block lazy loading in development

The best fix is making the mistake loud. Laravel can throw an exception whenever a relationship is lazy loaded, so N+1 bugs fail in development instead of reaching production.

// AppServiceProvider::boot()
Model::preventLazyLoading(! $this->app->isProduction());

How to spot them

  • Laravel Debugbar or Telescope in development shows query counts per request
  • DB::listen() or the query log can print every query in a test
  • A query count that grows with the number of rows is the telltale sign
  • Slow-query logging on MySQL catches the worst offenders in production

Other quick wins

Add indexes on columns you filter and join on, paginate instead of loading everything, and use chunkById() for large batch jobs so you never hold a whole table in memory. Measure before and after, because the right fix depends on where the time is actually spent.

If an application has become slow and you need someone to track down why, that is what my production debugging and maintenance service is for.

Original article written by Saad Ali Khan. Code samples are illustrative and free to adapt in your own projects.

Want this done right in your project?

Send a short description and I'll reply by email with questions or a suggested approach.