PHP
Optimizing Database Queries with Eloquent Eager Loading
Learn how to prevent the N+1 query problem and significantly boost your Laravel application's performance by eager loading related Eloquent models.
<?php
// Imagine you have a Post model that 'hasMany' Comments.
// Without eager loading (N+1 problem):
$posts = App\Models\Post::all();
foreach ($posts as $post) {
echo $post->title . ": " . $post->comments->count() . " comments
";
}
// With eager loading using the 'with()' method:
$posts = App\Models\Post::with('comments')->get();
foreach ($posts as $post) {
echo $post->title . ": " . $post->comments->count() . " comments (eager loaded)
";
}
// Eager loading multiple relationships:
$users = App\Models\User::with(['posts', 'profile'])->get();
// Eager loading with constraints:
$activePosts = App\Models\Post::with(['comments' => function ($query) {
$query->where('approved', true);
}])->get();
How it works: This snippet demonstrates how to use Eloquent's `with()` method for eager loading. Without eager loading, accessing a relationship (e.g., `$post->comments`) within a loop triggers a separate database query for each iteration, leading to the 'N+1 query problem'. Eager loading fetches all related records in a single or a few separate queries, drastically reducing database load and improving application performance. It can also be used to eager load multiple relationships or apply constraints to the eager-loaded relationships.