Getting all users with a specific role when using teams #1999
-
I was using the teams feature in spatie's roles and permissions but I figured out that when using this function: it only returns the users with role1 who are associated with the team id set in the session my question: how can I get all of the users of different teams? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 9 replies
-
Make your own relation // User model
public function roles_all(): BelongsToMany
{
return $this->morphToMany(
config('permission.models.role'),
'model',
config('permission.table_names.model_has_roles'),
config('permission.column_names.model_morph_key'),
PermissionRegistrar::$pivotRole
);
}
// get all users with a specific role
Users::whereHas('roles_all', fn($query) => $query->whereIn("name", ['role1']))->get();
// or
Users::whereRelation('roles_all', "name", 'role1')->get();
// Also, you could get all roles, from all teams with this
Users::with('roles_all')->get(); |
Beta Was this translation helpful? Give feedback.
-
@erikn69 How could I join the "team ID" model to this via my controller? I thought something like this might work but it doesn't: $user = $user->load([
'roles_all' => function ($query) {
$query->join('companies', function ($join) {
$join->on('roles_all.company_id', '=', 'companies.id');
});
}
]); |
Beta Was this translation helpful? Give feedback.
-
@erikn69 Thanks for your reply. I've given this a go, it doesn't give me any errors, this is my code now: $user = $user->load([
'roles_all' => function ($query) {
$query->leftJoin('companies', function ($join) {
$join->on(config('permission.table_names.roles').'.company_id', '=', 'companies.id');
});
}
]); Any ideas why I don't see my |
Beta Was this translation helpful? Give feedback.
Make your own relation