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

ThomHofstede's avatar

Show user roles from other table

Hello,

I want to get the specific user role for the logged in user, but I don't know what to do after getting the Auth::user. I have the following code now:

public function index()
{
    $roles = Role::all();
    return view('admin.dashboard', ['roles' => $roles]);
}

My view where I try to get the role:

                            <p>
                                {{ucfirst(Auth::user()->name)}} - {{ Auth::user()->$roles->name }}
                                <small>Member since {{ucfirst(Auth::user()->created_at->format("M d Y"))}}</small>
                            </p>

Everything is in the same table except the user roles and I dont know how to get into there, i tried this: {{ Auth::user()->$roles->name }}

0 likes
4 replies
ThomHofstede's avatar

@thefuzzy0ne Hi, I've made this relation

public function users()
 {
  return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id');
 }

  public function roles()
    {
        return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
    }
pieter771's avatar

I don't know if this is the best solution but this works, if someone have another better method please tell it.

Controller should look like this

    public function index()
    {
        $user = User::all();
        return view('admin.dashboard');
    }
@foreach 
    (Auth::user()->roles as $roles) 
        {{ $roles->name }}
@endforeach
1 like
ovvessem's avatar

Hi @ThomHofstede ,

Like @thefuzzy0ne mentioned the best thing is to create a relationship between User and Role model to (eager) load the associated roles. I am assuming a user can have more then one role.

public function roles() {
    return $this->belongsToMany(Role::class); 
}

You can then use this in your blade template:

@foreach(auth()->user()->roles as $role)
<li>{{ $role->name }}</li>
@endforeach 

Please or to participate in this conversation.