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

lukeboy_2002's avatar

User Roles

Can someone help me. In an other question I have asked for a tutorial for a role and permission system.

I watched some tutorials and now I implemented Spatie Roles and Permissions. To show a rol belongs to a user I used {{ $user->roles()->pluck('name')->implode(' ') }} Now I want to show the different roles in a different color. I tried but I can't get I wright.

0 likes
7 replies
Sinnbeck's avatar

Predefined colors or just random colors?

If random but always the same, install https://github.com/KaloyanYosifov/php-string-to-color

$stringToColor = new \StringToColor\StringToColor();
$roles = $user->roles()->pluck('name')->map($role) use ($stringToColor) {
    return [
      'name' => $role, 
      'color'=> $stringToColor->handle($role)
   ];
});
1 like
mabdullahsari's avatar

You do a simple translation of roles to different colors.

What have you tried so far?

lukeboy_2002's avatar

@mabdullahsari I tried a lot of things. like

if ($user->roles()->pluck('name') = 'user')

if ($user->roles()->id='3'')

if ($user->role(user))

if ($user->hasRole(user))

lukeboy_2002's avatar

@Sinnbeck I have not tried it

In my table users I want to have a pill with the user role. if is Role is admin I want te display the pill in red, if the role Is user the pill has to be yellow etc.

Sinnbeck's avatar

@lukeboy_2002 so you want it to be stored in the database I assume. So each role has its own color in there

A simple solution is to store the role colors in a different table. Then make your own color() relationship as a ->hasOne(RoleColor::class)

https://spatie.be/index.php/docs/laravel-permission/v5/advanced-usage/extending#extending

You can then just do $role->color->color

You can also change the roles table to have a color column and use that directly

tykus's avatar

Just make a lookup with either Role name or (ideally) the id as the key and the color/CSS class as the value:

public function getColorAttribute()
{
	return [
        1 => 'red',
        2 => 'green',
        // ... etc
    ][$this->id] ?? 'default-pill-color';
}

Now, each Role has a color attribute available to the view:

@foreach ($user->roles as $role)
	<span class="{{ $role->color }}">{{ $role->name }}</span>
@endforeach

Please or to participate in this conversation.