F
Filamentβ€’2w ago
aksl

Laravel permissions

I'm looking for the best way to manage the super admin role. Currently in my User resource I have this :
Select::make('roles')
->relationship('roles', 'name')
->multiple()
->preload()
->searchable()
Select::make('roles')
->relationship('roles', 'name')
->multiple()
->preload()
->searchable()
So a user who can modify roles can assign super_admin to everyone. how would you make it so that only a super_admin sees the super_admin role? Maybe you should disable it altogether? thanks πŸ™‚
5 Replies
Dennis Koch
Dennis Kochβ€’2w ago
Probably something like this:
->relationship('roles', 'name', function ($query) {
if (! $user->isSuperAdmin()) {
$query->whereNot('name', 'super-admin');
}
});
->relationship('roles', 'name', function ($query) {
if (! $user->isSuperAdmin()) {
$query->whereNot('name', 'super-admin');
}
});
H4L1M
H4L1Mβ€’2w ago
Am doing it with checking the user id 1 So only user 1 can add/delete super admins Other Super admins can't add or delete other super admins
awcodes
awcodesβ€’2w ago
You can certainly do what you need, just be aware that basing it on a user id will create problems down the road if that user ever gets deleted for whatever reason.
Exi
Exiβ€’2w ago
You can write a custom rule to check that Like:
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$role = Role::find($value);

if (! auth()->user()?->hasRole('super_admin') && $role->name === 'super_admin') {
$fail('...');
}
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$role = Role::find($value);

if (! auth()->user()?->hasRole('super_admin') && $role->name === 'super_admin') {
$fail('...');
}
}
Matthew
Matthewβ€’2w ago
That'll be a total nightmare to maintain in the future. Take 3 minutes to make a migrate to add a column, update your mode, and write the function and the test. Future you will be very grateful.

Did you find this page helpful?