#Role enum with spatie laravel-permission

6 messages · Page 1 of 1 (latest)

lilac dome
#

The way I render it is as following

<span class="inline-flex items-center px-2 py-1 text-xs font-medium text-{{ $user->role->color() }}-700 bg-{{ $user->role->color() }}-100 rounded-full">
                                    {{ $user->role->label() }}
                                </span>
#

My enum class

<?php

namespace App\Enums;

enum Role: string
{
    case SuperAdmin = 'super-admin';
    case Admin = 'admin';
    case Employee = 'employee';
    case Customer = 'customer';

    public function label()
    {
        return match ($this)
        {
            static::SuperAdmin => 'Super-admin',
            static::Admin => 'Admin',
            static::Employee => 'Employee',
            static::Customer => 'Customer',
        };
    }

    public function color()
    {
        return match ($this)
        {
            static::SuperAdmin => 'purple',
            static::Admin => 'red',
            static::Employee => 'sky',
            static::Customer => 'gray',
        };
    }
}
#

Inside User.php (model)

/**
     * Get the user's role.
     */
    public function getRoleAttribute()
    {
        return Role::from($this->getRoleNames()->first());
    }
#

Since i'm using spatie's laravel-permission package, I have to create a accessor that returns the role name along with 'casting'/'binding' it to the enum

#

This approach works flawlessly, except for rendering the colors properly. The only color that works when returned is the one of the customer's

hexed stump