Santiago Ramirez
Santiago Ramirez

Reputation: 317

print user role laravel Spatie

i'm filling a table with users information now I want to get his role too, i'm using Spatie/permission library

<thead>
  <tr>
    <th>Name</th>
    <th>Last name</th>
    <th>E-mail</th>
    <th>Role</th>
    <th>Status</th>
    <th>Edit</th>
    <th>Delete</th>
  </tr>
</thead>

<tbody>
 @foreach (App\User::all() as $user)
    <tr>
      <td>{{ __($user->person->first_name)}}</td>
      <td>{{ __($user->person->last_name) }}</td>
      <td>{{ __($user->email) }}</td>
      <td>{{ __() }}</td>
      <td>{{ __($user->active) }}</td>
      <td><button class="edit btn btn-sm btn-warning" value="{{ __($user->id)}}">Edit</button></td>
      <td><button class="delete btn btn-sm btn-danger" value="{{ __($user->id)}}">Delete</button></td>
    </tr>
  @endforeach
</tbody>

I don't know if I have to create the relationship on User model or with the Spatie installation the relationships are ready to use

Upvotes: 0

Views: 4231

Answers (2)

Urja Satodiya
Urja Satodiya

Reputation: 412

You can use like below if you need to show all roles assigned to user with comma seperated

$user->roles->pluck('name')->implode(',');

pluck() will return an array so we can use implode() with it.

Or

// get the names of the user's roles
$user->getRoleNames()->pluck('name')->implode(','); // getRoleNames() returns a collection

I hope this is useful.

Upvotes: 2

Naxon
Naxon

Reputation: 1414

In order to get the name of the first role:

$user->roles->first()->name

Or you can get all of the roles separated by a comma:

$user->roles->implode(', ');

Upvotes: 1

Related Questions