Using Laravel Eloquent, you can add 'where clauses' on a relationship count condition

Pascal Baljet, 14 Dec 2016


Eloquent provides an easy way to add a relationship count condition to a query. Say you have a User model and a Role model which are related to each other using a many-to-many relationship. Using Eloquent it is very easy to get all Users that have one or more Roles or doesn't have Roles at all:

UserModel::has('Roles')->get();
UserModel::doesntHave('Roles')->get();

This is really cool but there is more! You can actually add 'where clauses' to the count condition. This is handy if you want to fetch all user with a specific role, for example all admins:

UserModel::whereHas('Roles', function($query) {
    $query->where('label', 'admin');
})->get();

UserModel::whereDoesntHave('Roles', function($query) {
    $query->where('label', 'admin');
})->get();

I think this is a very elegant solution!