A page that lists orders along with each customer's name runs fine against ten seed rows locally, then falls over the moment the table crosses a few thousand records in production. Response time climbs almost linearly with the number of rows rendered, even though the SQL query sitting in the controller looks perfectly reasonable. The culprit is almost never the query you wrote, it's the ones Eloquent quietly generates on your behalf while the view renders.
The mechanism: why Eloquent multiplies queries
Eloquent lazy loads relationships by default. When you access $order->customer, the model doesn't have that data yet: the magic __get method intercepts the access, notices the relation hasn't been loaded, and fires an immediate SQL query to fetch it. As long as that access happens once, it's not a problem. The problem appears when that access happens inside a loop.
// OrderController.php
public function index()
{
$orders = Order::latest()->paginate(20);
return view('orders.index', ['orders' => $orders]);
}
{{-- orders/index.blade.php --}}
@foreach ($orders as $order)
<tr>
<td>{{ $order->id }}</td>
<td>{{ $order->customer->name }}</td>
<td>${{ number_format($order->total_cents / 100, 2) }}</td>
</tr>
@endforeach
This executes one query to fetch the 20 orders, then one additional query per row to fetch the associated customer, for a total of 21 queries instead of a couple. With a 50-row page and two or three relations touched in the view (customer, shipping address, latest payment), a single page easily reaches 150 queries, each carrying its own network round trip to the database. Locally, against an in-memory SQLite database or a MySQL instance on the same host, that latency is negligible. In production, against a remote database under a loaded connection pool, it becomes the dominant factor in response time.
Diagnosing before fixing
Before fixing anything, measure it. Three complementary tools:
Laravel Telescope or Laravel Debugbar in a development environment display the exact number of queries executed per page along with their content. A page reporting "47 queries" for a list of 20 items is an immediate red flag.
DB::listen gives a quick diagnostic without installing a package, useful for pair debugging or for temporarily instrumenting a staging environment:
DB::listen(function ($query) {
Log::debug($query->sql, $query->bindings);
});
Model::preventLazyLoading(), available since Laravel 10, turns the problem into an explicit failure instead of a silent slowdown. Placed in AppServiceProvider::boot() and enabled outside production, it throws a LazyLoadingViolationException the moment an unloaded relation is accessed:
// AppServiceProvider.php
public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction());
}
That single line turns every latent N+1 into an immediate test failure or local 500 error, long before a customer finds it by scrolling an order list that takes too long to load.
The fix: targeted eager loading
The fix is to tell Eloquent, before the loop runs, which relations will be needed, so it fetches them in a single additional query using a WHERE IN clause.
public function index()
{
$orders = Order::with('customer')->latest()->paginate(20);
return view('orders.index', ['orders' => $orders]);
}
This drops the count from 21 queries to 2: one for the orders, one for every customer involved via SELECT * FROM customers WHERE id IN (...). Dot notation handles nested relations:
$orders = Order::with('customer.address', 'latestPayment')->latest()->paginate(20);
And if the view only renders a subset of the customer's columns, restricting the loaded columns reduces the amount of data transferred, as long as the foreign key is explicitly included:
$orders = Order::with(['customer:id,name'])->latest()->paginate(20);
For a one-off need on a collection already fetched (say, after an in-memory conditional filter), loadMissing() is preferable to load(): it only loads relations that aren't already present, avoiding a redundant query if they were loaded earlier up the call stack.
The tradeoffs of eager loading everything
Sprinkling with() everywhere isn't a universal fix. Three common traps:
Default over-fetching. Setting protected $with = ['customer'] directly on the Order model forces that relation to load on every usage of the model, including ones that don't need it, such as a billing job that only reads the total amount. Explicit, per-use-case eager loading at the controller or repository level keeps fine-grained control over what's actually necessary.
Row duplication with hasMany relations. Unlike belongsTo (an order has exactly one customer), eager loading a hasMany or belongsToMany relation inside a paginated collection doesn't duplicate PHP rows thanks to Eloquent's internal grouping, but the volume of data transferred can still be high if the relation holds many rows per parent. In that case, withCount() for a simple tally, or a dedicated subquery, is often cheaper than loading the entire collection just to display its size.
Cost on large exports. For a 100,000-row export, paginate() with eager loading still works, but combining with() with cursor() needs a closer look: cursor() doesn't play well with with() on hasMany relations because of row-by-row hydration. In that case, chunk() or lazy() with explicit eager loading is the safer choice.
When simple eager loading isn't enough
Some N+1 cases resist a plain with():
Polymorphic relations. An Activity model with a morphTo() relation to Order, Invoice or Payment still fires one query per polymorphic type encountered, even with with('subject'). The fix is morphWith(), which specifies which relations to eager load for each concrete type:
$activities = Activity::with(['subject' => function ($morphTo) {
$morphTo->morphWith([
Order::class => ['customer'],
Invoice::class => ['client'],
]);
}])->get();
Accessors hiding a query. A getStatusLabelAttribute() method that calls $this->latestPayment->status triggers an invisible N+1 that doesn't show up in the controller or view code, because it's nested inside the model definition. Telescope will surface it, a plain controller read won't. The fix is eager loading latestPayment upstream, combined with a whenLoaded check in the accessor to avoid a silent fallback into lazy loading when someone forgets.
API Resources. An OrderResource used as a collection (OrderResource::collection($orders)) repeats the same looping pattern as Blade, but the responsibility for eager loading stays with the controller, not the resource itself, which ideally shouldn't contain any query at all.
For truly critical volumes (dashboards aggregating millions of rows), ORM-level eager loading hits a structural ceiling: every extra query is still a network round trip. A denormalized SQL view, a periodically refreshed aggregate table, or a read replica dedicated to analytical queries becomes more relevant at that point than another layer of with().
Guarding against regressions in tests
Fixing an N+1 once is not the same as keeping it fixed. A later refactor that adds one more field to a Blade component, or a new API resource field that quietly touches a relation, can reintroduce the exact same problem without anyone noticing, since the page still renders correctly, just slower. The only reliable guard is a query-count assertion baked into the test suite, not a comment reminding developers to "remember to eager load."
public function test_order_list_does_not_trigger_n_plus_1(): void
{
Order::factory()->count(10)->for(Customer::factory())->create();
$queryCount = 0;
DB::listen(function () use (&$queryCount) {
$queryCount++;
});
$this->get(route('orders.index'))->assertOk();
$this->assertLessThanOrEqual(3, $queryCount);
}
This test fails the moment someone adds an unguarded relation access back into the view, regardless of whether they understand why the count matters. It's a cheap test to write, and unlike a manual Telescope check, it runs on every pull request. Pairing it with Model::preventLazyLoading() in the testing environment is even stronger: instead of merely counting queries, the test actively fails with a clear exception naming the exact relation and model that triggered an unguarded lazy load, which points a reviewer straight at the line to fix instead of leaving them to guess from a query count alone.
Takeaway
N+1 isn't a bug you fix once and move on from: it's a structural risk every time a relation gets touched inside a loop, whether that loop lives in a Blade view, an accessor, or an API resource. Turning on Model::preventLazyLoading() in development and tests converts these silent leaks into immediate, reproducible failures, long before a customer finds them in the form of a page that takes eight seconds to load.
