← Back to all snippets
PHP

Filter Models Based on Related Model Attributes

Efficiently filter parent models by conditions on their related child models using Eloquent's `whereHas` method in Laravel.

use App\Models\User;
use App\Models\Post;

$activeUsersWithPublishedPosts = User::whereHas('posts', function ($query) {
    $query->where('published', true);
})->get();

// You can also use `orWhereHas` for alternative conditions
$usersWithEitherPublishedOrDraftPosts = User::whereHas('posts', function ($query) {
    $query->where('published', true);
})->orWhereHas('posts', function ($query) {
    $query->where('status', 'draft');
})->get();
How it works: The `whereHas` method allows you to filter results based on the existence of related models that satisfy specific conditions. It's crucial for efficiently retrieving parent records where their associated child records meet certain criteria, without loading all related data, thus preventing N+1 issues and optimizing database queries. This is different from `with` which eager loads the relation, as `whereHas` only filters the parent model.

Need help integrating this into your project?

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

Hire DigitalCodeLabs