PHP
Laravel Eloquent Eager Loading to Solve N+1 Problem
Optimize Laravel database queries by learning how to use Eloquent eager loading with 'with()' to efficiently fetch related models and prevent the N+1 query problem.
// 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
$posts = App\Models\Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name; // User is already loaded, single query for all users
}
// 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();
How it works: This snippet demonstrates how to use Eloquent's `with()` method for eager loading. Instead of executing a separate query for each related model accessed in a loop (the N+1 problem), eager loading fetches all related models in a single, separate query, significantly improving performance for pages displaying many related records. It can also include constraints on the eager-loaded relationships.