Home > Blockchain >  Laravel 6 in index blade how can I show only users who have roles and their roles in the table
Laravel 6 in index blade how can I show only users who have roles and their roles in the table

Time:11-24

In index.blade.php, I wrote these codes to show users who have roles

<thead>
    <tr>
        <th scope="col">Name</th>
        <th scope="col">Email</th>
        <th scope="col">Roles</th>
        <th scope="col">Actions</th>
    </tr>
</thead>
<tbody>
    @foreach($users as $user)
        <tr>
            <td>{{ $user->name }}</td>
            <td>{{ $user->email }}</td>
            <td>{{ $user->roles }}</td>
            <td>Show</td>
        </tr>
    @endforeach
</tbody>

And I wrote these codes in UserController,

 $userId = \DB::table('role_user')->get()->pluck('user_id');
 $users = User::find($userId);

 return view('admin.index', compact('users'));

And I got these in the website:

[{"id":1,"name":"User Administrator","description":null,"created_at":"2021-11-23 03:06:49","updated_at":"2021-11-23 03:06:49","pivot":{"user_id":1,"role_id":1}}]

[{"id":2,"name":"Moderator","description":null,"created_at":"2021-11-23 03:06:49","updated_at":"2021-11-23 03:06:49","pivot":{"user_id":2,"role_id":2}}]

How can I only display the names in the table role column?

CodePudding user response:

When calling user->roles, you're most likely calling towards a relation on your User model. This means that you're returning a collection. If you place a collection in curly braces in blade ({{ $user->roles }}), Laravel automatically calls toArray() on each model, and a json_encode on the result, which results in the JSON strings you end up seeing.

You only want the names, however, so it'd be better to grab those values and convert them to a string. An option of doing so is by plucking the name, and imploding the result:

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

You have to call toArray() on the pluck() result, else you'll have a collection instead of an array, which implode does not work with.

CodePudding user response:

If the user is logged in and his role is to be displayed, you can use this in your blade:

{{ Auth::user()->roles->pluck('name') }}

Or you would like to display the rools of another user, then you can do it as follows:

// in Controller fetch the user:
$user = User::find(42);

// in your Blade:
{{ $user->roles->pluck('name') }}

In this context, you have a number of methods that you can use:

  • roles
  • hasRole
  • hasAnyRole
  • hasAllRoles
  • getRoleNames
  • Related