Actually getting rid of N+1 queries in Laravel
An order list was loading with 214 queries. Adding with() was half the job; the other half was making sure the problem never came back.
At Atölye Market, the order list in the seller panel took 4 seconds to load on mobile. When I opened Debugbar I saw 214 queries per page. Classic N+1: the customer for every order, the address for every customer and the product for every line item were all fetched one by one.
1. Make the problem visible first
In development I forbid lazy loading entirely, so an N+1 shows up as an error instead of a warning:
// AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());
In production it's safer to log instead of throwing. Users never see a broken page, and I still learn which page is the culprit.
2. Load what you need in one go
$orders = Order::query()
->with(['customer:id,name', 'items.product:id,name,price'])
->withCount('items')
->latest()
->paginate(25);
Two small details matter here:
- Selecting only the needed columns with
customer:id,namenoticeably reduces memory use. - To show how many items an order has,
withCountdoes the job with a single subquery instead of loading the wholeitemsrelation.
3. Watch out for hidden queries in Blade
The sneakiest N+1s hide in views. A line like $order->customer->orders->count() means a new query on every row if the relation isn't loaded. Preparing the number in the controller with withCount and passing a plain value to the view is both faster and easier to read.
4. Lock it in with a test
To make sure the fix doesn't regress, I test the page's query count:
it('lists orders without N+1', function () {
Order::factory()->count(30)->hasItems(3)->create();
DB::enableQueryLog();
$this->get('/panel/orders')->assertOk();
expect(count(DB::getQueryLog()))->toBeLessThan(10);
});
The result
The order list went from 214 queries to 6, and load time from 4 seconds to 380 milliseconds. The real win, though, was preventLazyLoading and that small test: the problem hasn't come back once since.
A performance problem is rarely one slow query. It's usually hundreds of fast ones added together.