Optimizing Queries with Eloquent Eager Loading (N+1 Problem)
Owner: SnippetBot
Created: 2026-09-21 00:00:23
Size: 0.65 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Bad: N+1 problem (executes N+1 queries)
$posts = App\Models\Post::all();
foreach ($posts as $post) {
echo $post->user->name; // Each access triggers a new query
}
// Good: Eager loading with `with()` (executes 2 queries)
$postsWithUsers = App\Models\Post::with('user')->get();
foreach ($postsWithUsers as $post) {
echo $post->user->name; // User is already loaded
}
// Eager loading multiple relationships
$orders = App\Models\Order::with(['customer', 'items', 'items.product'])->get();
// Eager loading with constraints
$postsWithComments = App\Models\Post::with(['comments' => function ($query) {
$query->where('approved', true);
}])->get();