F
Filament12mo ago
Nono

Restricting Access to a Custom Filament Page Based on User Role

Hello everyone, I'm currently working on a Filament project and have created a custom page named ApproveMaterials. I need to restrict access to this page so that only users with the 'admin' role can view it. However, I'm facing challenges in implementing this restriction. Could anyone offer insights or guidance on the best way to restrict access to a custom Filament page based on user roles (and the make invisible the navigationLabel in the sidebar) ? Any tips or examples would be greatly appreciated! Thank you in advance for your help.
6 Replies
toeknee
toeknee12mo ago
This is a really easy implementation usually, eaither by using Policies.... as recommended. But if it is just the single page, put:
public function canView() {
return auth()->user()->hasRole('Admin');
}
public function canView() {
return auth()->user()->hasRole('Admin');
}
or whatever role checker function you have on your user instance.
Nono
NonoOP12mo ago
I've tried but it isn't working, i can still have access while i'm a simple 'user' and not an 'admin'.
einnlleinhatt_
einnlleinhatt_12mo ago
Do you have a role in your user ?
Nono
NonoOP12mo ago
Yes I have a ‘user’ role
einnlleinhatt_
einnlleinhatt_12mo ago
Maybe you can try filament shield plugin Do you mind sharing your code?
DrByte
DrByte12mo ago
Do you mean you can actually use the page? Or just that it still shows in the nav menu? I've used the following to control access to some pages:
public static function shouldRegisterNavigation(): bool
{
// two options here, pick one and adapt to what you need.
return auth('admin')->user()->hasAnyRole(['Super-Admin']);
return filament()->auth()->user()->email === '[email protected]';
}

public function mount(): void
{
abort_unless(self::shouldRegisterNavigation(), 403);
}
public static function shouldRegisterNavigation(): bool
{
// two options here, pick one and adapt to what you need.
return auth('admin')->user()->hasAnyRole(['Super-Admin']);
return filament()->auth()->user()->email === '[email protected]';
}

public function mount(): void
{
abort_unless(self::shouldRegisterNavigation(), 403);
}
So I guess you could then also add:
public static function canView(): bool
{
return self::shouldRegisterNavigation();
}
public static function canView(): bool
{
return self::shouldRegisterNavigation();
}
(or maybe canView() can't be static in your page? depends where you're using it)
Want results from more Discord servers?
Add your server