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

StarShines's avatar

Auth::User -> Role -> Title Error

Hello,

I have a User model, which has a defined relationship like this:

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

The roles table has a column "Title", which includes the value "Admin" or "Accountant"

Now, I am trying to show in my blade view certain table rows using this and its giving me Undefined array key "title" error:

@if ( Auth::user()->roles['title'] == "Admin")

@end if

I have even tried the below but it's not working:

@if ( Auth::user()->roles->title == "Admin")

@end if

Your help is highly appreciated.

Thank you Regards

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue with the code is that roles is a collection of roles, not a single role. Therefore, you need to loop through the collection to access each role's title. Here's an example of how to do it:

@foreach (Auth::user()->roles as $role)
    @if ($role->title == "Admin")
        // Do something
    @endif
@endforeach

Alternatively, if you only want to check if the user has the "Admin" role, you can use the contains method:

@if (Auth::user()->roles->contains('title', 'Admin'))
    // Do something
@endif
tykus's avatar

If you are using Spatie's permissions package, there is a hasRole method

Please or to participate in this conversation.