Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tomu1202's avatar

Send user data with roles to view and display it

I have problem with user roles, which i'd like to send to the view and display it.

Controller

    public function manage(Request $request)
    {
        //Check role
        $request->user()->authorizeRoles('admin');
        
        $users = User::all();
        $roles = Role::all();
        return view('users.manage')
                                    ->with('users', $users)
                                    ->with('roles', $roles);
    }

View

                        @foreach($users as $index => $user)
                             <tr>
                                <td>{{ $index +1}}</td>
                                <td>{{$user->name}}</td>
                                <td>{{$user->surname}}</td>
                                <td>ROLE HERE</td>
                                <td>{{$user->department}}</td>
                            </tr>
                        </tbody>
                        @endforeach 
0 likes
3 replies
robbyrr's avatar

Does a user have multiple roles? Otherwise you could set up a relationship and acces it like $user->role in your loop.

tomu1202's avatar

User can have only one role. i have user table, role table and intermediary table 'role_user'. Now i send data to view like this

    public function manage(Request $request)
    {
        //Check role
        $request->user()->authorizeRoles('admin');

        $users = User::all();
        $roles = Role::all();

        return view('users.manage', compact('users', 'roles'));
    }

and i don't know how to display role belongs to user :/

                        @foreach($users as $index => $user)
                             <tr>
                                <td>{{ $index +1}}</td>
                                <td>{{$user->name}}</td>
                                <td>{{$user->surname}}</td>
                                <td>ROLE HERE</td> 
                // when i use {{$user->roles}} it returns me whole table in view. 
                // i don't have idea how to gain only name of this role: 
                // concept {{$user->roles->name}} 
                                <td>{{$user->department}}</td>
                            </tr>
                        </tbody>
                        @endforeach 
tomu1202's avatar
tomu1202
OP
Best Answer
Level 1

i resolved problem: {{$user->roles->first()->role}}

Please or to participate in this conversation.