Batman55's avatar
Level 32

trying to figure out how to write a "Relationship does not have" correctly

In a when statement, I am trying to not include super-admins in the list. It would be the opposite of whereBelongsTo($superAdminRole)

select *
from users
join roles on users.role_id = roles.id
where roles.auth_code != 'super-admin'
0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To exclude users with the "super-admin" role in a query using Eloquent in Laravel, you can use the whereDoesntHave method. This method allows you to filter out records that have a certain relationship. In your case, you want to exclude users who have a role with the auth_code of "super-admin".

Here's how you can achieve this:

$users = User::whereDoesntHave('role', function ($query) {
    $query->where('auth_code', 'super-admin');
})->get();

In this example, role is the relationship method defined in your User model that relates to the Role model. The whereDoesntHave method will exclude any users that have a role with the auth_code of "super-admin".

Make sure that your User model has a relationship defined like this:

public function role()
{
    return $this->belongsTo(Role::class);
}

This setup will ensure that your query correctly excludes users with the "super-admin" role.

1 like
vincent15000's avatar

I think that you can also do the same with this code.

$users = User::where('role.auth_code', '!=', 'super-admin')->get();
Batman55's avatar
Level 32

@vincent15000 Currently I am using the code snippet below as the role model has a code (int) and an auth_code (string) attribute on it. In this current case it makes it easy, as the less amount of privileges the higher the code value.

In this query we are not allowing users to see other users with higher privileges than them in the list.

For example:

super-admin has a code = 0

admin has a code = 1

manager has a code = 2

->whereDoesntHave('role', function ($query) use ($request) {
	$query->where('code', '<', $request->user()->role->code);
})
1 like

Please or to participate in this conversation.