authorization in NavigationItem

I have this in my AppServiceProvider class:
Filament::serving(function () {
Filament::registerNavigationGroups([

NavigationGroup::make()
->label('Admin')
->collapsible(false)
->items([
NavigationItem::make('roles')
->visible(auth()->user()->can('manage-admin-settings')),
NavigationItem::make('users')
->visible(auth()->user()->can('manage-admin-settings'))
])


]);
});
Filament::serving(function () {
Filament::registerNavigationGroups([

NavigationGroup::make()
->label('Admin')
->collapsible(false)
->items([
NavigationItem::make('roles')
->visible(auth()->user()->can('manage-admin-settings')),
NavigationItem::make('users')
->visible(auth()->user()->can('manage-admin-settings'))
])


]);
});
Based on the documentation, it indicates I can add a NavigationItem and conditionally show/hide it based on the role of the user. However, I believe that at this point in the execution, the app is still booting and the authorized user isn't available. I'm getting an error that I can't call can() on null.
3 Replies
Jon Mason
Jon MasonOP15mo ago
awcodes
awcodes15mo ago
Try it in a callback. visible(fn() => auth->can)
Jon Mason
Jon MasonOP15mo ago
that didn't work either...the link I posted seems to be the way to do it, but that method returns false when it shouldn't, and when I dd() inside of my policy, it's not even hitting the policy at all. In my UserResource:
public static function shouldRegisterNavigation(): bool
{
//dd(auth()->user()->can('manage-admin-settings')); <--- returns false, but should return true.
return auth()->user()->can('manage-admin-settings');
}
public static function shouldRegisterNavigation(): bool
{
//dd(auth()->user()->can('manage-admin-settings')); <--- returns false, but should return true.
return auth()->user()->can('manage-admin-settings');
}
class UserPolicy
{
public function manageAdminSettings(User $user): bool
{
dd('manageAdminSettings'); <-- isn't getting here at all.
return $user->hasAdminRole();
}
}
class UserPolicy
{
public function manageAdminSettings(User $user): bool
{
dd('manageAdminSettings'); <-- isn't getting here at all.
return $user->hasAdminRole();
}
}
It works if I don't use the policy and I just do something like: return auth()->user()->hasRole('System Admin'); in the shouldRegisterNavigation method. so it seems to be policy related.
Want results from more Discord servers?
Add your server