PHP
Filtering Parent Models Based on Related Model Attributes with Eloquent `whereHas`
Learn to efficiently filter your parent models in Laravel Eloquent by applying conditions on their related models using the `whereHas` method.
<?php
use App\Models\Post;
use App\Models\User;
// Example: Get all posts that have comments by a specific user
$postsWithCommentsByUser = Post::whereHas('comments', function ($query) {
$query->where('user_id', 1);
})->get();
// Example: Get all users who have at least one post
$usersWithPosts = User::has('posts')->get();
// Example: Get all users who don't have any posts
$usersWithoutPosts = User::doesntHave('posts')->get();
How it works: This snippet demonstrates how to query parent models based on the existence or attributes of their related models using `has()`, `doesntHave()`, and `whereHas()`. `has()` checks for the existence of at least one related record. `doesntHave()` checks for the non-existence. `whereHas()` allows adding specific conditions to the related model's query before checking for existence, making it powerful for complex filtering.