PHP
Querying Models That Lack a Specific Relationship
Discover how to use Laravel Eloquent's `whereDoesntHave` method to efficiently retrieve models that do not have any related records for a given relationship.
use App\Models\Post;
use App\Models\User;
// Find all posts that have no comments
$postsWithoutComments = Post::whereDoesntHave('comments')->get();
// Find all users who haven't created any posts
$usersWithoutPosts = User::whereDoesntHave('posts')->get();
// Find all posts without approved comments (with a condition)
$postsWithoutApprovedComments = Post::whereDoesntHave('comments', function ($query) {
$query->where('approved', true);
})->get();
// Find users who have posts, but none of their posts have comments
$usersWithPostsButNoCommentsOnThem = User::whereHas('posts')
->whereDoesntHave('posts.comments') // Chained relationship
->get();
How it works: The `whereDoesntHave` method allows you to filter models based on the absence of a related record. This is highly useful for scenarios like finding "orphan" records or items that haven't met a specific condition in their related data. You can also pass a closure to add additional constraints to the relationship query.