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

kevinwakhisi's avatar

Attributes

how can i get attributes from a relationship model this works when i get roles in a table

 public function getRoleColorAttribute()
    {
        # code...
        return [
            'super-admin' => 'primary',
            'admin' => 'info',
        ][$this->name] ?? 'warning';
    }

the the role color doesn't work when its in relationship of users

 <td>
    @foreach ($user->roles as $role)
         <a href="#" class="badge badge-light-{{$role->role_color}}">
              {{ $role->name }}
          </a>
      @endforeach
  </td>
0 likes
4 replies
Tray2's avatar
Tray2
Best Answer
Level 73

That is because it returns the whole array and not the color.

If you are using php8 you can do something like this

return match($this->role) {
    'super-admin' => 'primary',
    'admin' => 'info',
    default => 'warning'
  };
kevinwakhisi's avatar

@Tray2 still doesn't return anything. Sorry i know how to unset this as the best answer

Sinnbeck's avatar

What do you get instead? Always warning? An error?

kevinwakhisi's avatar

@Sinnbeck when i query the roles only, the colours work fine, but in my scenario i am querying the users with roles and the small section that i posted are the roles that each user has. At the moment it doesn't return anything

public function render()
    {
        return view('livewire.admin.users', [
            'users' => \App\Models\User::with('roles')
                ->paginate($this->perPage)
        ]);
    }

Please or to participate in this conversation.