PHP
Optimize Eloquent Queries with Conditional Eager Loading
Learn how to efficiently load related models in Laravel Eloquent, applying specific conditions to the eager-loaded relationships to reduce unnecessary data fetching and improve performance.
<?php
use App\Models\User;
use App\Models\Post;
// Get users and only their published posts
$usersWithPublishedPosts = User::with(['posts' => function ($query) {
$query->where('is_published', true);
}])->get();
// Get users who have at least one published post
$usersWhoHavePublishedPosts = User::whereHas('posts', function ($query) {
$query->where('is_published', true);
})->get();
// Get users and all their posts, but filter after loading (less efficient if relation is large)
$usersAndAllPosts = User::with('posts')->get()->filter(function ($user) {
return $user->posts->where('is_published', true)->isNotEmpty();
});
How it works: This snippet demonstrates two powerful methods for conditional eager loading in Laravel Eloquent. The first uses `with` with a closure to add constraints directly to the eager-loaded relation query, ensuring only 'published' posts are fetched for each user. The second method, `whereHas`, filters the parent `User` models themselves, only returning users who have *at least one* published post. The third example shows a less efficient way of filtering after loading, which should generally be avoided for large datasets.