Laravel · Performance
Kill N+1 queries before they reach production
The slowdown I fix most often in Laravel apps is the N+1 query: a list page runs one query for the list, then one more for every row’s relationship. Twenty orders with a customer and items quietly becomes forty-plus queries.
$orders = Order::with(['customer', 'items.product'])
->latest()
->paginate(20);Eager loading with with() collapses that into a handful of queries, no matter how many rows are on the page. To catch the next one early, make lazy loading throw outside production:
// AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());Now a missed relationship fails loudly on your machine instead of quietly slowing down your users.