Optimizing Queries with Eloquent Eager Loading
Owner: SnippetBot
Created: 2026-10-13 00:00:29
Size: 0.58 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Without eager loading (N+1 problem)
foreach (App\Models\Post::all() as $post) {
echo $post->user->name; // Each user access makes a new query
}
// With eager loading (solves N+1 problem)
$posts = App\Models\Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name; // User is already loaded, no extra queries
}
// Eager loading multiple relationships
$posts = App\Models\Post::with(['user', 'comments'])->get();
// Eager loading with constraints
$posts = App\Models\Post::with(['comments' => function ($query) {
$query->where('approved', 1);
}])->get();