Skip to content

Laravel N+1 query problem: eager loading and detection

Published December 1, 2026 · Updated December 3, 2026

An N+1 query happens when code loads a list with one query, then runs one more query for each item in that list. In Laravel it almost always comes from an Eloquent relationship read inside a loop. The fix is eager loading: ask for the relationship up front with with(), and Eloquent replaces N queries with one.

What an N+1 looks like in Eloquent

Take a blog: each post belongs to an author.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Post extends Model
{
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

A controller lists the posts and the view prints each author's name:

$posts = Post::latest()->take(50)->get();

foreach ($posts as $post) {
    echo $post->author->name;
}

Relationships read as properties are lazy loaded: Eloquent queries the author the first time $post->author is accessed, and it does so separately for every post. The query log shows the pattern:

select * from `posts` order by `created_at` desc limit 50
select * from `users` where `users`.`id` = ? limit 1
select * from `users` where `users`.`id` = ? limit 1
select * from `users` where `users`.`id` = ? limit 1
-- ... 47 more

That is 51 queries for one page. Each is fast on its own, which is why the problem is easy to miss: a few milliseconds per query, multiplied by the number of rows, multiplied by the number of relationships in the template. The Laravel documentation uses the same example with books and authors: 25 books, 26 queries.

Fixing it with eager loading

Name the relationship when you build the query:

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

Eloquent now runs two queries, whatever the number of posts:

select * from `posts` order by `created_at` desc limit 50
select * from `users` where `users`.`id` in (3, 8, 12, 19, ...)

Several relationships, nested relationships

Pass an array for several relationships, and use dot syntax for a relationship of a relationship:

$posts = Post::with(['author', 'tags', 'comments.author'])->get();

comments.author loads every comment of every post, then the author of each comment, in one query per level. The nested array form does the same and reads better when a branch has several children:

$posts = Post::with([
    'author' => ['profile', 'team'],
])->get();

You can also limit the columns loaded, as long as you keep the primary key and the foreign keys Eloquent needs to match rows: Post::with('author:id,name').

Constrained eager loading

When you only need part of a relationship, pass a closure. Eloquent applies it to the single eager query:

$posts = Post::with(['comments' => function ($query) {
    $query->where('approved', true)->latest();
}])->get();

withWhereHas('comments', fn ($query) => ...) filters the posts and loads the matching comments with the same condition.

Loading after the fact: load() and loadMissing()

Sometimes the collection already exists, for example when a relationship is needed only in one branch of the code. load() eager loads on an existing collection or model, loadMissing() does it only for relationships not loaded yet:

$posts = Post::latest()->get();

if ($request->boolean('with_comments')) {
    $posts->load('comments.author');
}

$posts->loadMissing('author');

Counts and sums without loading the rows

Displaying "12 comments" next to each post does not require the comments. withCount() adds a comments_count attribute with a subquery, and withSum(), withAvg(), withMin(), withMax() and withExists() work the same way:

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

foreach ($posts as $post) {
    echo $post->comments_count.' comments, '.$post->comments_sum_votes.' votes';
}

On models already retrieved, loadCount() and loadSum() are the deferred versions. Calling $post->comments()->count() inside the loop is the N+1 version of the same need. The aggregates section of the documentation lists every variant.

The child that reads its parent

A loop over $post->comments that prints $comment->post->title loads the post again for each comment. The chaperone() method, on the hasMany definition or at eager loading time, sets the parent on each child without a query:

$posts = Post::with([
    'comments' => fn ($comments) => $comments->chaperone(),
])->get();

Making lazy loading fail in development

Laravel can refuse lazy loading altogether. In AppServiceProvider::boot():

use Illuminate\Database\Eloquent\Model;

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

Any lazy load then throws Illuminate\Database\LazyLoadingViolationException, outside production only. Keep that argument: in production, an exception would turn a slow page into a broken one. The guard applies to models that were retrieved as part of a collection of several rows, which is exactly where an N+1 lives. A single model fetched with find() can still lazy load its relationships without complaint.

To log instead of throwing, for example on a staging environment where you want a list rather than a crash:

Model::handleLazyLoadingViolationUsing(function (Model $model, string $relation) {
    $class = $model::class;

    info("Attempted to lazy load [{$relation}] on model [{$class}].");
});

Model::shouldBeStrict() turns on preventLazyLoading, preventSilentlyDiscardingAttributes and preventAccessingMissingAttributes at once. Give it the same condition: Model::shouldBeStrict(! $this->app->isProduction()). See Configuring Eloquent strictness.

Laravel also offers Model::automaticallyEagerLoadRelationships(), which lazy eager loads a relationship for the whole collection the first time it is accessed on one model. The feature was introduced as beta in Laravel 12, so read the current documentation before relying on it.

The N+1 that eager loading does not catch

preventLazyLoading() only watches relationships read as properties. Several common patterns run a query per row without ever lazy loading anything:

  • Explicit queries in a loop. Order::where('user_id', $user->id)->sum('total') or $post->comments()->count() inside a foreach are ordinary queries. No exception, one query per row. Use withCount(), withSum() or a single grouped query.
  • Accessors. An accessor that runs a query, or reads a relationship, executes once per model. If the attribute is in $appends, it runs for every row during JSON serialization, far from the code that built the list.
  • Blade components. A component that receives an ID and fetches its own model, or calls a relationship method, runs its query once per instance. Pass the already loaded model instead.
  • API resources. 'author' => new UserResource($this->author) lazy loads for each item of a ResourceCollection. Write $this->whenLoaded('author') and eager load in the controller; $this->whenCounted('comments') does the same for counts. See Conditional relationships.
  • Polymorphic relationships. Eager loading a morphTo relationship runs one query per related type, which is expected. The nested relationships of each type are not loaded unless you say so with morphWith(), or loadMorph() on an existing collection.
  • Livewire. A computed property is memoized only for the duration of a single component request, so its query runs again on every update unless it is declared with #[Computed(persist: true)]. A child component rendered for each row of a list runs its own queries per instance. See the Livewire documentation on computed properties.

Seeing the queries locally

The simplest check is the query log, here in a feature test:

use Illuminate\Support\Facades\DB;

DB::enableQueryLog();

$this->get('/posts');

dump(count(DB::getQueryLog()));

DB::listen() gives you every query as it runs, with its SQL, bindings and time. A few lines in a service provider flag a statement repeated within one request:

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

public function boot(): void
{
    if (! $this->app->isLocal()) {
        return;
    }

    $seen = [];

    DB::listen(function (QueryExecuted $query) use (&$seen) {
        $seen[$query->sql] = ($seen[$query->sql] ?? 0) + 1;

        if ($seen[$query->sql] === 10) {
            Log::warning('Same query run 10 times in one request', ['sql' => $query->sql]);
        }
    });
}

This is a development aid: the counter lives for the PHP process, which is one request under PHP-FPM but not under Octane. For a total-time budget per request, DB::whenQueryingForLongerThan() calls a closure when database time passes a threshold. Both are described in Listening for query events.

Laravel Telescope records every query of a request with its duration, and the third-party Laravel Debugbar shows the query list of the current page in the browser. The guide on Laravel Pulse and Telescope compares the first-party tools, and Telescope in production covers what it costs to keep it running there.

Why the costly ones show up in production

A local database with twenty seeded rows produces an N+1 of twenty queries, which nobody notices. Production has the customer with 3,000 orders, the admin export nobody opens locally, the report page used once a month, the queued job that iterates over every subscriber. The same code, with real volumes, turns into hundreds of queries per request. Queued jobs are a frequent source because nobody watches them render: the guide on monitoring Laravel queues covers that side.

preventLazyLoading() only covers the pages you actually open during development, and only lazy loading. What remains is measuring the real traffic.

With Quiet Guard

Quiet Guard's performance monitoring measures every request and job of your production application and flags N+1 queries per page. The Laravel package counts, within one request or job, a SELECT run at least ten times with at least five different sets of values. The values themselves never leave your server: only the normalised shape of the query is sent, once a minute, in an aggregated summary. When the same page shows that pattern on three page views within 24 hours, a problem opens and an alert names the page (alerts start 24 hours after the first summary). Each route also gets its call count, durations and SQL time, and the slow queries are listed.

It is included in the Indie and Studio plans. Install the package and add your project key:

composer require quiet-guard/laravel-monitor
MONITOR_KEY=your-project-api-key
MONITOR_PERFORMANCE=true

See Installation and the performance documentation for what is measured and what is not.

If you are also weighing Laravel Nightwatch, our comparison page lists the differences with their sources.

In Quiet Guard

Performance monitoring

A slow page or an N+1 query raises no exception. Quiet Guard measures every request and every job of your Laravel applications, without sampling, and tells you which pages slow down and why.

Exception tracking

Every exception your Laravel applications throw, grouped by cause rather than by occurrence, with the full stack trace and the commit that introduced it.

Alerts and notifications

An alert when an issue appears or comes back, when the site goes down, when a task stops pinging or a certificate nears expiry. By email, Slack, Discord, Teams or webhook, and in the dashboard.