Tricks

Conditions on user menu items based on roles

Jan 27, 2023
sheldon
Admin panel

You can not use auth()->user() in AppServiceProvider::class.

  1. Create a middleware
php artisan make:middleware UserMenuItemMiddleware
  1. Register Middleware (config/filament.php)
'middleware' => [
'auth' => [
Authenticate::class,
UserMenuMiddleware::class, // <here
],
'base' => [
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
VerifyCsrfToken::class,
SubstituteBindings::class,
DispatchServingFilamentEvent::class,
MirrorConfigToSubpackages::class,
InitializeTenancyBySubdomain::class,
PreventAccessFromCentralDomains::class,
],
],
  1. Now add your logic inside UserMenuItemMiddleware
public function handle(Request $request, Closure $next)
{
 
if (auth()->user()->hasRole("super_admin")) {
Filament::registerUserMenuItems([
'link' => UserMenuItem::make()->label('Custom Label')->url("Your Link")
]);
}
 
Filament::registerUserMenuItems([
'account' => UserMenuItem::make()->label('My Profile')->url('/admin/my-profile')
]);
 
 
return $next($request);
}

That its now you can have conditions on your custom user menu items.

No comments yet…