Why is my Laravel page running hundreds of queries? (The N+1 problem, explained)

You're loading a list of models, then touching a relationship on each one inside a loop. Laravel runs 1 query for the list + 1 query per row for the relationship. That's the N+1 problem. The fix is to tell Eloquent up front which relationships you need, with with(), so it loads them in one extra query instead of N.

Published
Read time 4 min
Reads 22

What it looks like

A blog index that shows each post's author:

// Controller
$posts = Post::all();

// Blade
@foreach ($posts as $post)
    {{ $post->title }} by {{ $post->author->name }}
@endforeach

This looks harmless, but here's what hits the database:

select * from posts;                       -- 1 query
select * from users where id = 1 limit 1;  -- post #1
select * from users where id = 2 limit 1;  -- post #2
-- ...one more for every post

100 posts means 101 queries. On your laptop with 5 rows of seed data you won't notice. In production with real data, the page crawls.

Why it happens: relationships are lazy-loaded by default. $post->author isn't fetched until the moment you access it, and it's fetched for that one post only.

How to spot it

  • Laravel Debugbar (barryvdh/laravel-debugbar, local only): the Queries tab shows the count, and lots of near-identical queries are the giveaway.
  • Laravel Telescope: the Queries and Requests tabs show how many queries each request ran.
  • Quick check without packages:
DB::enableQueryLog();
// ...run the code...
dd(count(DB::getQueryLog()));

Rule of thumb: if the query count grows with the number of rows on the page, you have an N+1.

Fix 1: Eager load with with()

$posts = Post::with('author')->get();

Now it's always 2 queries, whether you have 10 posts or 10,000:

select * from posts;
select * from users where id in (1, 2, 3, ...);

It also works for several and nested relationships:

Post::with(['author', 'category', 'comments.user'])->get();

You can select only the columns you need. Always include the key used to match the relationship (id here), or it comes back empty:

Post::with('author:id,name')->get();

Fix 2: Already have the models? Use load()

If the collection came from somewhere else (route model binding, a service, a paginator), load the relationship afterwards:

$posts->load('author');

// only loads it if it isn't loaded already
$posts->loadMissing('author');

Fix 3: Counting? Use withCount()

This is a very common hidden N+1:

@foreach ($posts as $post)
    {{ $post->comments()->count() }} comments  {{-- 1 query per post --}}
@endforeach

Instead, let the database count everything in one query:

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

// in Blade
{{ $post->comments_count }} comments

withSum, withAvg, withMin, withMax and withExists work the same way.

Where N+1 likes to hide

  • Blade views and components: the query is in the view, so it doesn't show up when you read the controller.
  • API Resources: $this->author->name inside a resource runs once per item. Eager load in the controller, and use $this->whenLoaded('author') in the resource so it only includes data that was already loaded.
  • Accessors / appended attributes that touch a relationship.
  • Queued jobs and commands looping over thousands of records. Nobody sees a slow page, but the job takes forever.

Catch it before production

Make Laravel throw an exception whenever something is lazy-loaded, but only outside production:

// app/Providers/AppServiceProvider.php
use Illuminate\Database\Eloquent\Model;

public function boot(): void
{
    Model::preventLazyLoading(! app()->isProduction());
}

Now any missing with() fails loudly in local and staging (LazyLoadingViolationException), instead of quietly slowing down production. Available since Laravel 8.43.

Laravel 12.8+: automatic eager loading

Newer Laravel versions can detect the access and eager load for you:

// for a single collection
$posts = Post::all()->withRelationshipAutoloading();

// or app-wide, in AppServiceProvider::boot()
Model::automaticallyEagerLoadRelationships();

It's a good safety net, especially for deep chains like $order->client->owner->company. Explicit with() is still the clearest option, because the next developer can see exactly what the query loads.

Checklist

  • Looping over models and touching a relationship? → with()
  • Already have the collection? → load() / loadMissing()
  • Only need a number? → withCount()
  • API Resources → eager load in the controller + whenLoaded()
  • Turn on preventLazyLoading() outside production so it can't sneak back in