Eager Loading and Query Scopes
Prevent N+1 queries with eager loading and reuse logic with query scopes.
The N+1 Problem
Lazy loading runs one query per model when accessing a relationship inside a loop — catastrophic at scale.
<?php
$posts = Post::all(); // 1 query
foreach ($posts as $post) {
echo $post->author->name; // 1 query per post = N+1 total!
}Eager Loading with with()
Solve N+1 by eager-loading relationships upfront in one extra query.
<?php
$posts = Post::with("author")->get(); // 2 queries total
foreach ($posts as $post) {
echo $post->author->name; // no extra query
}All lessons in this course
- Eloquent Models and Migrations
- CRUD with Eloquent
- Eloquent Relationships
- Eager Loading and Query Scopes