The N+1 is one of the easiest performance bugs to ship without noticing. The code looks innocent: a loop over some models, reaching for a relationship inside it. Eloquent makes that line so natural to write that you rarely think about the query it fires. Multiply it by the number of rows on the page and a fast endpoint quietly becomes a slow one.
Why the name?
The "1" is the initial query that returns a list of N rows. The "N" is the N follow-up queries (one per row) to load related data. For 50 posts loaded with their author, that's 51 total queries instead of the 2 you actually need.
The classic Laravel example
// 1 query: SELECT * FROM posts ORDER BY ... LIMIT 50
$posts = Post::latest()->take(50)->get();
foreach ($posts as $post) {
// 50 queries: SELECT * FROM users WHERE id = ?
echo $post->author->name;
} // 2 queries: 1 for posts, 1 batched for all authors
$posts = Post::with('author')->latest()->take(50)->get();
foreach ($posts as $post) {
echo $post->author->name; // already in memory
} Why it matters
Every query has network and protocol overhead, roughly 1-5ms when the database is on another host. The queries themselves might be fast, but 50 round-trips stack up: a page that should run in 50ms runs in about 100-300ms. Scale that to 500 items and the round trips alone add 0.5 to 2.5 seconds.
Because the extra cost grows with the list, fixing an N+1 pays off most on the pages with the longest lists.
Where they come from
Almost always a relationship accessed inside a loop, but the loop isn't always where you'd look. A few places they hide:
- In Blade.
@foreach ($posts as $post) {{ $post->author->name }}is an N+1 even though there's no visible query in your controller: the relationship resolves lazily when the view renders. - In API resources. A
PostResourcethat returns$this->author->namefires one query per item in the collection, and the loop lives inside Laravel's serialization where you never see it. - After a refactor. Someone adds
with('author')when they write the endpoint. A later change adds a second relationship ($post->comments) and only the first stays eager-loaded. It passed review and degrades in production as data grows. That's the case worth monitoring for, because code review already missed it once.
How to detect N+1 in production
Model::preventLazyLoading() catches them in development. In production you need an APM that groups repeated query fingerprints per request. The signal is "the same normalized SQL fired 47 times in one request."
NightOwl gives you the data to spot it without auto-flagging: every statement is fingerprinted, and the Queries page shows a Calls column per pattern. The request detail page puts every query the request fired on its timeline, gives identical SQL a shared colour, and adds a Duplicates tab that lists only the repeated queries. The diagnosis is yours, not an automated threshold.