PHP
Filter Models by Relationship Existence with Laravel Eloquent whereHas
Efficiently query parent models based on the existence or specific conditions of their related child models using Laravel Eloquent's `whereHas` method.
use App\Models\User;
use App\Models\Post;
// Get all users who have at least one post
$usersWithPosts = User::has('posts')->get();
// Get all users who have at least one published post
$usersWithPublishedPosts = User::whereHas('posts', function ($query) {
$query->where('is_published', true);
})->get();
// Get all users who DO NOT have any posts
$usersWithoutPosts = User::doesntHave('posts')->get();
// Get all users who DO NOT have any published posts
$usersWithoutPublishedPosts = User::whereDoesntHave('posts', function ($query) {
$query->where('is_published', true);
})->get();
echo "Users with at least one post:
";
foreach ($usersWithPosts as $user) {
echo "- " . $user->name . "
";
}
echo "
Users with at least one published post:
";
foreach ($usersWithPublishedPosts as $user) {
echo "- " . $user->name . "
";
}
How it works: Laravel Eloquent's `has` and `whereHas` methods are crucial for filtering parent models based on the presence or specific attributes of their related child models. `has('posts')` retrieves users who have *any* posts. `whereHas('posts', function ($query) { ... })` allows for more specific filtering, retrieving users who have posts matching certain criteria (e.g., `is_published = true`). Conversely, `doesntHave` and `whereDoesntHave` can be used to find parent models that *do not* have specific related records.