I'm using Laravel with Laratrust, How to print a role that's attached to an account?

711 views Asked by At

In my home page, I can print the name and email of a logged account using:
{{ Auth::user()->name }}
{{ Auth::user()->email }}

but when i want to print the role that attached to the account using this:
{{ Auth::user()->roles }}

it prints a collection of keys and values of all the data in the table instead, like this:
[{"id":3,"name":"mahasiswa","display_name":"Mahasiswa","description":"Mahasiswa","created_at":"2021-03-22T13:09:14.000000Z","updated_at":"2021-03-22T13:09:14.000000Z","pivot":{"user_id":4,"role_id":3,"user_type":"App\\Models\\User"}}]

I just want to extract the name or display_name.

So, i'm using {{ Auth::user()->roles->where('name')->first() }} but it still shows the same collection but without the "[]" brackets.

2

There are 2 answers

0
john_smith On BEST ANSWER

Thanks for the answers guys! I appreciated it.

But I just found the answer here https://stackoverflow.com/a/39357511/15471776

So, I changed my code to {{ Auth::user()->roles->first()->display_name }} and it displays the role name that attached to my logged account perfectly.

1
Flak On

You should get first record then get field.

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

Here is reference from docs

https://laravel.com/docs/8.x/collections#method-get