PHP
Efficiently Load Eloquent Relationships with Eager Loading
Prevent N+1 query problems in Laravel by eagerly loading related models using the `with()` method, significantly improving application performance and reducing database calls.
// Without eager loading (N+1 problem)
$posts = App\Models\Post::all();
foreach ($posts as $post) {
echo $post->user->name; // Each access generates a new query
}
// With eager loading
$posts = App\Models\Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name; // All users loaded in a single query
}
// Eager loading multiple relationships and nested relationships
$books = App\Models\Book::with('author', 'genre.category')->get();
// Eager loading with constraints
$users = App\Models\User::with(['posts' => function ($query) {
$query->where('active', 1);
}])->get();
How it works: Eager loading solves the N+1 query problem by loading all related models for a collection in a single query. Instead of querying for each relationship individually within a loop, the `with()` method instructs Eloquent to fetch related data upfront, drastically reducing database calls and improving performance. It can be applied to multiple and nested relationships, and even accept constraints within the eager loading definition.