PHP

Filter Models Based on Related Model Existence with `has` and `whereHas`

Use Eloquent's `has()` and `whereHas()` methods to retrieve parent models that have (or do not have) specific related records or related records matching certain conditions.

// In a controller or service
use App\Models\Post;
use App\Models\User;

// Get all users who have at least one post
$usersWithPosts = User::has('posts')->get();

// Get all users who have at least 5 posts
$usersWithManyPosts = User::has('posts', '>=', 5)->get();

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

// Get all posts that have at least one comment from a specific user
$postsWithUserComments = Post::whereHas('comments', function ($query) {
    $query->where('user_id', 1); // Assuming user ID 1
})->get();

// Get all posts that have at least one approved comment
$postsWithApprovedComments = Post::whereHas('comments', function ($query) {
    $query->where('approved', true);
})->get();

// Get all posts that do NOT have any comments (using 'doesntHave')
$postsWithoutComments = Post::doesntHave('comments')->get();

// Get all users who have posts where the title contains 'Laravel'
$usersWithSpecificPosts = User::whereHas('posts', function ($query) {
    $query->where('title', 'like', '%Laravel%');
})->get();
How it works: The `has()` method retrieves models that have at least one related record. You can specify a count constraint for more granular filtering (e.g., `has('posts', '>=', 5)`). The `whereHas()` method allows you to add further constraints to the related model query itself. This is powerful for filtering parent models based on specific conditions of their child relationships, offering precise control over your data retrieval. `doesntHave()` is used to retrieve models that do not have any related records.

Need help integrating this into your project?

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

Hire DigitalCodeLabs