PHP
Eager Loading Multiple Eloquent Relationships
Optimize database queries by eager loading multiple related models in Laravel Eloquent, preventing the N+1 query problem and significantly improving application performance.
use App\Models\User;
use App\Models\Post;
$usersWithPostsAndComments = User::with(['posts', 'posts.comments'])->get();
foreach ($usersWithPostsAndComments as $user) {
echo "User: " . $user->name . "
";
foreach ($user->posts as $post) {
echo " Post: " . $post->title . "
";
foreach ($post->comments as $comment) {
echo " Comment: " . $comment->content . "
";
}
}
}
How it works: This snippet demonstrates how to eager load multiple relationships and even nested relationships using the `with()` method. Eager loading retrieves all related models in a single, optimized query instead of running a separate query for each related item (the N+1 problem). This significantly reduces the number of database queries and improves the performance of your Laravel application, especially when dealing with lists of models and their associated data.