Skip to main content
Tutorial Free

Filament: Show/Hide Fields based on Roles and Permissions

April 11, 2024
2 min read

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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

IK
Igor Krivtsov ✓ Link copied!

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

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.