Protone Media logo

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

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!

Related posts

Want to stay up-to-date on Laravel news and packages?

Pascal Baljet on Twitter

Follow me on Twitter: @pascalbaljet

Pascal Baljet on Twitter

Subscribe to my YouTube channel

© 2013-2024 Protone Media B.V. Hosted with Eddy Server Management.