PHP

Filtering Models Based on Related Model Existence in Eloquent

Filter parent models in Laravel Eloquent using `has` and `whereHas` to find records based on the existence of related models or specific conditions in their relationships.

// Find all posts that have at least one comment
$postsWithComments = App\Models\Post::has('comments')->get();

// Find all posts that have at least one comment by a specific user (ID 1)
$postsWithUserComments = App\Models\Post::whereHas('comments', function ($query) {
    $query->where('user_id', 1);
})->get();

// Find all posts that do NOT have any comments
$postsWithoutComments = App\Models\Post::doesntHave('comments')->get();

// Find all posts that do NOT have any comments by a specific user (ID 1)
$postsWithoutUserComments = App\Models\Post::whereDoesntHave('comments', function ($query) {
    $query->where('user_id', 1);
})->get();

// Find all users who have at least 5 posts
$usersWithManyPosts = App\Models\User::has('posts', '>=', 5)->get();
How it works: The `has` and `whereHas` methods allow you to filter parent models based on the existence of related models. `has` checks for any related models, optionally specifying a count. `whereHas` allows you to add specific conditions to the related model's query to filter parent models based on those conditions. Conversely, `doesntHave` and `whereDoesntHave` retrieve models that do not have any related records or specific related records, respectively. These methods are essential for complex data retrieval based on relationships.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs