PHP
Efficient Eager Loading with Relationship Constraints in Laravel Eloquent
Learn to efficiently load related models in Laravel Eloquent, preventing N+1 queries. This snippet demonstrates eager loading with specific constraints on the related data.
use App\Models\User;
use App\Models\Post;
// Load users and only their published posts
$usersWithPublishedPosts = User::with(['posts' => function ($query) {
$query->where('is_published', true)->latest();
}])->get();
foreach ($usersWithPublishedPosts as $user) {
echo "User: " . $user->name . "
";
foreach ($user->posts as $post) {
echo " Post: " . $post->title . "
";
}
}
// Load users, and for each post, also load its category
$usersWithPostsAndCategories = User::with('posts.category')->get();
foreach ($usersWithPostsAndCategories as $user) {
echo "User: " . $user->name . "
";
foreach ($user->posts as $post) {
echo " Post: " . $post->title . " (Category: " . ($post->category->name ?? 'N/A') . ")
";
}
}
How it works: This snippet demonstrates two powerful eager loading techniques. The first example loads all users and, for each user, only their `posts` that are marked as `is_published` and ordered by `latest`. This prevents the N+1 query problem while filtering the related data. The second example illustrates nested eager loading, where `posts` are loaded, and for each `post`, its associated `category` is also loaded, all in an optimized manner.