1

does anyone know how to show multiple roles that are under a user? I have setup my permissions so a user can be under multiple roles, which is set easily enough using the following

$user->assignRole(['Root', 'IT', 'HR']); // assigning roles

I am however having trouble showing all roles a user relongs to in the same way? Has anyone done this and knows how to? I simply want to show on a page which role a user belongs to.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Lachlan Young
  • 159
  • 12

3 Answers3

3

Refer to this link

https://spatie.be/docs/laravel-permission/v4/basic-usage/basic-usage

Get the names of the user's roles

$roles = $user->getRoleNames(); 

Returns a collection

Vicky Gill
  • 714
  • 1
  • 7
  • 21
2

if there are two tables (roles and user_roles) than you can check through inner join ('inner join' to check role must exist in 'roles' table that is assigned to a user) by passing user_id (user_id to get specific roles assigned by a user).

Atif Mahmood
  • 390
  • 1
  • 11
  • 2
    $get = DB::table('users_roles') ->join('roles', 'roles.id', '=', 'users_roles.role_id') ->select('roles.id', 'roles.name', 'users_roles.user_id') ->where('users_roles', $req->user_id) ->orderBy('roles.id', 'ASC') ->get(); – Atif Mahmood Apr 20 '21 at 06:16
1

You can get a collection of roles assigned to the user via $user->roles

ibra
  • 390
  • 3
  • 13