We've recently built Upserver.online, a sophisticated health checker for Laravel applications with support for databases, queues, broadcasting, mail, caching, security checks and it even monitors your uptime, DNS records, SSL certificates and mixed content. Create an account and follow us on Twitter!

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

December 14, 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!