Stage 2 · Lesson 10 of 10
The N+1 query problem
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
- CoursePaidGrokking Relational Database Design and Modeling
Design Gurus · Intermediate · $98 one-time
The modelling and normalisation decisions that stay with a codebase for years
- CourseFreeCS50's Introduction to Databases with SQL
Harvard University · Beginner
Free course from querying through schema design, indexes, transactions and scaling
Practise
Also worth your time
- Database Indexing Explained: B-Tree, Hash, Bitmap, R-Tree, and When to Use Each (opens in a new tab)Read
B-tree and composite indexes, plus the leftmost-prefix rule that trips people up
What sits under your queries: storage engines, transactions and isolation levels