N+1 Queries — Catch Them Before Your Client Does
Your page works, but the query count keeps growing. Learn how to spot and fix N+1 queries in Laravel before they reach production.

N+1 Queries — Catch Them Before Your Client Does
The page is fast and everything looks fine—until the data grows and your client notices the slowdown.
The problem is often not one expensive query. It is a small query running once for every record. That is the N+1 query problem.
How does it happen?
If you list orders with each customer's name:
$orders = Order::latest()->get();
foreach ($orders as $order) {
echo $order->customer->name;
}
Laravel runs one query for the orders, then another for every customer. One hundred orders can mean 101 queries without any error.
The fix
Load the relationship up front with with():
$orders = Order::with('customer')
->latest()
->get();
Instead of 101 queries, Laravel usually needs one for the orders and one for their customers.
How do you catch it?
Open the request in Laravel Telescope or Debugbar and check the query count. If the same query repeats with only the id changing, inspect the relationships used inside your loop.
You can also make Laravel catch the problem during development. Add this to AppServiceProvider:
use Illuminate\Database\Eloquent\Model;
public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction());
}
Laravel will now throw an exception when code tries to lazy-load a relationship.
Do not add with() to every relationship just in case. Load only what the page needs. If you only need the number of related records, use withCount():
$posts = Post::withCount('comments')->get();
Conclusion
Watch the query count, use with() for the relationships you need, and enable preventLazyLoading. Do not wait for the client to notice the slowdown first.