Backend development

Stage 2 · Lesson 10 of 10

The N+1 query problem

Relational databases and SQL

loads relationships lazily, only when you first touch them. So reading $order->customer->name in a loop or a view runs one query per order. That is the problem: 50 orders, 51 queries.

Eager load with Order::with('customer')->get(), which fetches all the customers in one extra query. Use withCount for counts, instead of loading whole collections. can catch the mistake for you.

Model::preventLazyLoading() in development throws an exception whenever a relation loads lazily. Laravel Debugbar or Telescope shows the queries for each request.

Common trapan or view that touches a relation the controller never loaded. The controller looks fine, and the extra queries hide in the output layer.

A question to check yourself, an AI practice session and 2 cheat sheet entries come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

Practise

Also worth your time

Mark this stage as not done?