F
Filament2mo ago
bouly

How to scope filament-shield roles

Hello, I'm wondering how to scope the roles of bezhanSalleh/filament-shield so that the Admin role can only be selected by admins. Here is my current code:
Select::make('roles')
->label(__('Role'))
->relationship('roles', 'name')
->preload()
->required()
->searchable(),
Select::make('roles')
->label(__('Role'))
->relationship('roles', 'name')
->preload()
->required()
->searchable(),
Thanks!
2 Replies
Tieme
Tieme2mo ago
take a look at https://filamentphp.com/docs/4.x/forms/select#customizing-the-relationship-query and try something like this
Select::make('roles')
->label(__('Role'))
->relationship(
name: 'roles',
titleAttribute: 'name',
modifyQueryUsing: fn (Builder $query) => auth()->user->hasRole('admin') ? $query : $query-whereNot('name','admin'),
)
->preload()
->required()
->searchable(),
Select::make('roles')
->label(__('Role'))
->relationship(
name: 'roles',
titleAttribute: 'name',
modifyQueryUsing: fn (Builder $query) => auth()->user->hasRole('admin') ? $query : $query-whereNot('name','admin'),
)
->preload()
->required()
->searchable(),
bouly
boulyOP2mo ago
Thanks. Yes I would do that if I do not find any other solution. But I would really appreciate a cleaner way with scope. + Could you confirm that this solution also prevent user from forcing the admin role? (in backend)

Did you find this page helpful?