Show/Hide Columns and Fields Based on Role

2024-05-17

When building a project, displaying different information for different Roles is essential. We would not want our Employees to see Critical information without specific access, so that is where we can conditionally hide/show fields and columns based on authorization level.

Often, a project requires hiding fields based on roles. This typically can be done in a few ways:

  • Using authorization rules
  • Using if conditions
  • Using Policies

But with Filament, things are different. Filament can't accept the conditions around the fields. But what it can do - hide fields, sections using ->hidden() method:

Forms\Components\Section::make('Employee Information')
->schema([
// ...
])
->hidden(auth()->user()->role == 'Admin'),

This has the same access limitation as the if condition but in the Filament way. Let's look at an example using Roles:

Forms\Components\Section::make('Employee Information')
->schema([
// ...
])
->hidden(auth()->user()->role->name !== 'Admin'),

This, of course, can be done on fields as well:

Forms\Components\TextField::make('name')
->hidden(auth()->user()->role->name !== 'Admin'),

Or even on the Table:

Tables\Columns\TextColumn::make('employee.name')
->hidden(auth()->user()->role->name !== 'Admin'),

Last, this is not limited to a single condition. We can use complex conditions using a callback:

Forms\Components\TextField::make('name')
->hidden(function () {
return auth()->user()->role->name !== 'Admin' && auth()->user()->role->name !== 'Manager';
}),

Or, we can even do the opposite - a ->visible() with the reverse condition:

Tables\Columns\TextColumn::make('employee.name')
->visible(auth()->user()->role->name === 'Admin'),

Most importantly, your check should always return a bool (true/false) value. Once you have that, you can hide fields based on your desired condition.


This example is based on our Customer Management CRM

A few of our Premium Examples: