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

david19's avatar

Function should render a array

Hello Team.

I have a little function here:

 public function getRoles()
    {
       
       foreach(Auth()->user()->roles as $role){
           
                 
           return $role->name;
               
           }

       
    }

If i call this function:

$this->getRoles();

This function render only a string with the last role, which wars rendered. How i save this data in a array, for render all the roles? Many thanks.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

If you return in the foreach loop, then the function returns.

You can get an array of the user's role names using:

auth()->user()->roles()->pluck('name')->all();

I don't believe that you need a separate getRoles function for this?

Next, "rendering an array" is something entirely different... how do you want them rendered as a comma-separated list

{{ auth()->user()->roles()->pluck('name')->implode(', ') }}

or as an unordered list:

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

Or something else???

1 like
orest's avatar
auth()->user()->roles()->pluck(‘name’);
1 like

Please or to participate in this conversation.