PHP
Solving N+1 Query Problem with Eloquent Eager Loading
Optimize Laravel Eloquent queries by preventing the N+1 problem using eager loading with `with()`, significantly improving application performance for related data retrieval.
// Before (N+1 problem)
$posts = App\Models\Post::all();
foreach ($posts as $post) {
echo $post->user->name; // Each call makes a new query
}
// After (Eager loading)
$posts = App\Models\Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name; // User is loaded with posts in one query
}
// 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('is_approved', true);
}])->get();
How it works: This snippet demonstrates how to solve the common N+1 query problem in Laravel Eloquent by using eager loading with the `with()` method. Instead of executing a separate query for each related model accessed in a loop, eager loading fetches all related models in a single or a few optimized queries, drastically reducing database load and improving application speed. It also shows how to eager load multiple relationships and add constraints to eager loaded relationships.