← Back to all snippets
PHP

Filtering Models by Related Model Conditions using whereHas()

Filter parent models in Laravel Eloquent based on specific conditions within their related models using the powerful `whereHas()` method for precise data retrieval.

use App\Models\Post;
use App\Models\Comment;

// Find all posts that have at least one comment containing 'awesome'
$postsWithAwesomeComments = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', '%awesome%');
})
->get();

echo "Posts with 'awesome' comments: " . $postsWithAwesomeComments->pluck('title')->implode(', ');

// Find all posts that *do not* have any comments (or specific comments)
$postsWithoutComments = Post::doesntHave('comments')->get();
echo "
Posts without any comments: " . $postsWithoutComments->pluck('title')->implode(', ');
How it works: The `whereHas()` method allows you to query a parent model based on the existence of a related model that meets certain conditions. This is extremely useful for complex filtering, such as finding all products that have reviews above a certain rating, or users who have posted more than 10 articles. The `doesntHave()` method is its inverse, finding parent models that do *not* have any related models (or none matching the given criteria).

Need help integrating this into your project?

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

Hire DigitalCodeLabs