Filament: Show/Hide Fields based on Roles and Permissions

In Filament forms, you may want to make specific fields in your forms visible or hidden, depending on the user's role. Here's how to do it.

Every Form field may have a method ->visible() with a callback function to check some condition. In this simple example, we'll use users.is_admin column, but your logic may be more complex.

app/Filament/Resources/PageResource.php:

public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\TextInput::make('title')
->columnSpanFull(),
Forms\Components\Textarea::make('content')
->columnSpanFull()
->rows(10)
->visible(fn() => auth()->user()->is_admin),
]);
}

There's an opposite method ->hidden() if you want to use the inverse condition.

Forms\Components\Textarea::make('content')
->hidden(fn() => ! auth()->user()->is_admin),

Finally, you may also restrict that field to be modified on Eloquent level in Laravel, with Mutator in the Model. This way, you will prevent the column to be saved, even if it happens outside of Filament form.

app/Models/Page.php:

class Page extends Model
{
// ...
 
public function setContentAttribute($value)
{
if (! auth()->user()->is_admin) {
return;
}
 
$this->attributes['content'] = $value;
}
}

Notice: In this case, I'm using an "older" Eloquent Mutators syntax of setColumnAttribute() which still works in the latest Laravel versions.


If you want more Filament examples, you can find more real-life projects on our FilamentExamples.com.

avatar

Thanks a lot. You're doing great stuff. These small Filament tips and tricks from real-world practical situations are awesome.

👍 2

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials