Phil
Phil

Reputation: 2236

Laravel: how to query to get all records except where relation has name column = admin

I have this query

$users = User::whereHas('roles', function($q){
    $q->where('name', '!=', 'admin');
})->get();

but I want to get all users including the ones that have no roles associated. Is there a way to query this?

Upvotes: 0

Views: 1939

Answers (1)

ceejayoz
ceejayoz

Reputation: 180014

You want to get the users where the number of roles matching 'admin' is less than one:

$users = User::whereHas('roles', function($q){
    $q->where('name', 'admin');
}, '<', 1)->get();

whereHasNot is coming, but not in a release yet.

Upvotes: 1

Related Questions