PHP

Filter Parent Models by Related Attributes Using Eloquent `whereHas`

Learn to retrieve parent models in Laravel Eloquent based on conditions applied to their related child models using the powerful `whereHas` method, enabling complex data filtering.

<?php

// Assuming User hasMany Posts, and Post has a 'status' column
// User.php
// public function posts() { return $this->hasMany(Post::class); }

// Retrieve all users who have at least one post with a 'published' status
$usersWithPublishedPosts = App\Models\User::whereHas('posts', function ($query) {
    $query->where('status', 'published');
})->get();

// Retrieve users who have more than 5 comments on any of their posts
$usersWithManyCommentsOnPosts = App\Models\User::whereHas('posts.comments', function ($query) {
    $query->having('count(comments.id)', '>', 5);
})->withCount('posts')->get(); // Using withCount for 'posts' is unrelated but often useful here

// Retrieve users who do NOT have any 'draft' posts
$usersWithoutDraftPosts = App\Models\User::whereDoesntHave('posts', function ($query) {
    $query->where('status', 'draft');
})->get();
How it works: The `whereHas()` method is invaluable when you need to filter parent models based on the existence or attributes of their related models. This snippet demonstrates how to find users who have posts with a specific status. It also shows `whereDoesntHave()` for filtering models that do *not* have a related model matching certain criteria. This provides powerful capabilities for complex data retrieval scenarios involving relationships.

Need help integrating this into your project?

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

Hire DigitalCodeLabs