Replies: 5 comments 7 replies
-
Did you try overriding use \Spatie\Permission\Traits\HasRoles {
getStoredRole as getStoredRoleTrait;
}
protected function getStoredRole($role): Role
{
if (is_object($role) && $role instanceof \BackedEnum) {
$roleClass = $this->getRoleClass();
return $roleClass->findByName($role->value, $this->getDefaultGuardName());
}
return $this->getStoredRoleTrait($role);
} |
Beta Was this translation helpful? Give feedback.
-
To make it work w/ if ($roles instanceof BackedEnum) {
return $guard
? $this->roles->where('guard_name', $guard)->contains('name', $roles->value)
: $this->roles->contains('name', $roles->value);
} |
Beta Was this translation helpful? Give feedback.
-
Just wanted to let you know I had the same idea and solved it like this: <?php
namespace App\Policies;
use App\Models\Role as RoleModel;
enum Role: string
{
case LEAD_ADMIN = 'lead_admin';
case GLOBAL_USER = 'global_user';
case ADMINISTRATOR = 'administrator';
case DEVELOPER = 'developer';
case PUBLISHER = 'publisher';
case AUTHOR = 'author';
public function id(): int
{
return RoleModel::whereName($this->value)->select('id')->first()->id;
}
} <?php
namespace App\Concerns;
use App\Policies\Role;
trait HasRoles
{
use \Spatie\Permission\Traits\HasRoles {
assignRole as protected spatieAssignRole;
}
public function assignRole(Role $role)
{
$this->spatieAssignRole($role->value);
return $this;
}
} And in the <?php
namespace App\Models;
use App\Concerns\HasRoles;
class User extends Authenticatable
{
use HasRoles;
.....
} |
Beta Was this translation helpful? Give feedback.
-
Is it a mistake that the Enums-feature is currently shown in the v5 documentation? It seems to be a v6 feature |
Beta Was this translation helpful? Give feedback.
-
Will there be support for this feature? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
We have a PHP 8.1 BackedEnum listing our application's roles.
This permits us to do the following:
However, this does not work with
assignRole()
:and we are instead required to do:
This appears to be due to HasRoles::getStoredRole accepting a string, numeric, or Role as argument.
I'd suggest this function have an additional check along the lines of:
so enums can be used as role names.
Beta Was this translation helpful? Give feedback.
All reactions