PHP
Filtering Models by Relationship Existence with Eloquent `has` and `whereHas`
Learn to filter parent models based on whether they have a related model or if a related model meets specific criteria using Laravel Eloquent's `has` and `whereHas`.
use App\Models\Post;
use App\Models\User;
// Get all posts that have at least one comment
$postsWithComments = Post::has('comments')->get();
// Get all posts that have comments and the comment content contains 'awesome'
$postsWithSpecificComments = Post::whereHas('comments', function ($query) {
$query->where('content', 'like', '%awesome%');
})->get();
// Get all users who have at least 3 posts
$usersWithManyPosts = User::has('posts', '>=', 3)->get();
// Get all posts that do NOT have any comments
$postsWithoutComments = Post::doesntHave('comments')->get();
How it works: Eloquent's `has()` and `whereHas()` methods are powerful tools for filtering parent models based on their relationships. `has()` filters results to only include models that have at least one related model. You can also specify a minimum number of related models. `whereHas()` goes a step further, allowing you to add specific conditions to the relationship query itself, filtering parent models only if their related models meet those criteria. `doesntHave()` is used to retrieve models that do not have any related models.