← Back to all snippets
PHP

Filtering Models Based on Related Model Existence

Use Laravel Eloquent's `has` and `whereHas` methods to filter parent models based on the existence of related models or specific conditions within those relationships.

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

// Get all users who have published at least one post in the last 7 days
$usersWithRecentPosts = App\Models\User::whereHas('posts', function ($query) {
    $query->where('published', true)
          ->where('created_at', '>=', now()->subDays(7));
})->get();

echo "Posts with Comments:
";
foreach ($postsWithComments as $post) {
    echo "- " . $post->title . "
";
}

echo "
Users with Recent Published Posts:
";
foreach ($usersWithRecentPosts as $user) {
    echo "- " . $user->name . "
";
}
How it works: The `has` method filters results to only include models that have at least one record for a given relationship. The `whereHas` method provides more granular control, allowing you to add specific conditions to the relationship query itself, filtering parent models based on related models meeting those criteria. These methods are crucial for complex data filtering.

Need help integrating this into your project?

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

Hire DigitalCodeLabs