Start free trial
Start free trial Log in

14-day free trial. No credit card.

How to Detect N+1 Queries in Laravel Production

Four concrete steps, from reproducing it locally with preventLazyLoading to catching it across real traffic.

  • Guide
  • 3 min read

How do I detect N+1 queries in Laravel production?

Call Model::preventLazyLoading() in AppServiceProvider to catch them in development, use eager loading (with(), load()) to fix them, and install a production APM that records query traces. NightOwl shows every query on each request's timeline and per-pattern call counts on the Queries page. Repeated SQL inside one request gets its own colour and shows up under the timeline's Duplicates tab, which is where an N+1 stands out.

Updated

The N+1 is the bug that ships green. It passes code review, passes your tests, runs fine in staging with a handful of seed rows, then degrades in production on a curve nobody's watching, because the cost is one extra query per row and your rows only grow. By the time a page is visibly slow, the N+1 has usually been there for months. That's the case for catching it three ways: a tripwire in development so new ones can't ship, the fix once you find one, and monitoring in production so the ones that slipped through surface as data instead of complaints.

1. Reproduce it locally

The fastest way to spot an N+1 is to count queries per request. Laravel Telescope (official, free) or laravel-debugbar both expose this.

Terminal
composer require laravel/telescope --dev
php artisan telescope:install
php artisan migrate

Installing with --dev means production won't have the package, so follow the local-only steps in the Telescope docs and register its service provider only in the local environment.

Load the slow page, then open /telescope/queries. If one endpoint fires 50+ similar queries, you have an N+1.

2. Fail loud in development

Eloquent lets you throw an exception whenever a relationship is lazy-loaded. This surfaces N+1s at the moment they're introduced, not weeks later when the page is slow.

app/Providers/AppServiceProvider.phpphp
<?php
namespace App\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Strict in dev and staging. Silent in production so we don't break
        // real users. We'll monitor N+1s in prod with an APM instead.
        Model::preventLazyLoading(! app()->isProduction());
    }
}

Now lazy loading a relation in development throws LazyLoadingViolationException with the exact relationship name. It only throws for models that came back from a multi-row result, which is where N+1s live; a model fetched on its own can still lazy load. Your tests will catch it too.

3. Fix it with eager loading

The idiomatic fix is with() at query time or load() after the fact.

Before: fires 51 queries for 50 posts

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

foreach ($posts as $post) {
    echo $post->author->name; // 1 query each, 50 extra queries
}

After: fires 2 queries

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

foreach ($posts as $post) {
    echo $post->author->name; // in-memory, no query
}

For nested relationships, use dotted syntax. Polymorphic morphTo relations eager load with a plain with(); reach for morphWith() only when each morph type needs its own nested relations. For column-selected eager loads:

php
Post::with([
    'author:id,name,avatar',
    'comments' => fn($q) => $q->latest()->limit(3),
    'tags',
])->paginate(25);

4. Catch them in production

preventLazyLoading only helps in environments you actively test. In production you need an APM that records the queries real requests run, so repeated patterns show up in the data.

Laravel Telescope is not production-grade: it stores every entry in your app's database (after the response, but in the same PHP process), has no aggregation across requests, and outside the local environment its default filter keeps only exceptions, failed requests, failed jobs, scheduled tasks and tagged entries. Options that are:

  • Laravel Nightwatch Cloud: official, records every query with trace context
  • NightOwl: BYOD Postgres dashboard on the same Nightwatch package
  • Sentry Performance: generic APM, weaker at Laravel-specific patterns

Spot the repeated query on a real slow request

NightOwl puts every query of a request on its timeline and gives repeated SQL a shared colour. Open a slow request, switch to the Duplicates tab, and a select that ran dozens of times stands out with its count. NightOwl doesn't label it as an N+1; the diagnosis stays yours.

No credit card needed.

Terminal
composer require nightowl/agent
php artisan nightowl:install
php artisan nightowl:agent

Frequently asked questions

Anything else, write to support@usenightowl.com

What is an N+1 query problem in Laravel?

An N+1 query happens when Laravel makes one query to fetch a list of parent records (the '1'), then one additional query per parent to fetch a related record (the 'N'). Loading 50 posts and then their authors one-by-one means 51 queries instead of 2. It's a common cause of slow Laravel endpoints.

How do I detect N+1 queries in Laravel locally?

Enable Laravel Telescope or Debugbar in development. Both show queries per request. For a code-level fix-first approach, call Model::preventLazyLoading(! app()->isProduction()) in AppServiceProvider so lazy loads throw a LazyLoadingViolationException outside production. In production, you need an APM that records the queries each real request runs.

How do I fix an N+1 query?

Use eager loading with with() or load(): User::with('posts')->get() fires two queries (users + posts) regardless of user count. For nested relations, use dotted syntax: User::with('posts.comments'). Polymorphic morphTo relations eager load with a plain with(); use morphWith() inside it when each morph type needs its own nested relations. For conditional eager loading, use with(['relation' => fn($q) => $q->where(...)]).

Can I detect N+1 queries in production?

Yes, but not with Telescope (it's not production-grade). You need an APM that captures query traces per request and groups identical query patterns. NightOwl records every query against your app and shows per-pattern Calls on the Queries page. Open a slow request: its timeline gives identical SQL the same colour, and the Duplicates tab lists only the repeated queries. A select that repeats 50 times in one request is your N+1.

Should I always eager load everything?

No. Over-eager-loading is the opposite mistake. If you eager-load a relation you only use on 10% of records, you load data you don't need. Profile real traffic and eager-load based on actual access patterns, not defensive assumptions.

Does preventLazyLoading break production?

Only if you leave it on in production. The canonical pattern is Model::preventLazyLoading(! app()->isProduction()): strict in dev and staging, silent in production. In production you detect N+1s via monitoring, not by throwing exceptions that would break user requests.

What's the performance impact of an N+1 query?

Each query costs at least one network round trip on top of actual execution, roughly 1-5ms when the database is on another host. A 100-item page with an N+1 adds 100 queries, so about 100-500ms of extra latency at those figures: enough to turn a 200ms page into one that takes 300-700ms. The problem scales linearly with list size.

Related

Flat pricing, whatever your traffic does

Every plan starts with a 14-day free trial. No credit card needed.

Hobby
$5 a month

One app for a side project. Issues and alerts, with a 14-day dashboard window.

Start my 14-day trial
TeamRecommended
$15 a month

Up to 3 apps and 5 people per team. Full history, the MCP server, data clearing and agent health.

Start my 14-day trial
Agency
$69 a month

Unlimited client apps and people, one overview of every app, and apps you can hand over.

Start my 14-day trial