FilamentF
Filamentβ€’7mo ago
Kaesa Lyrih

How to apply Laravel Policy to Filament Actions (Export/Import/Custom Actions)?

Hi everyone πŸ‘‹

I'm using FilamentPHP and trying to integrate Laravel Policies into my actions, both default (like Export/Import) and custom ones (like a PublishPost action on a PostResource).

---

πŸ”’ Use Case 1: Export / Import Authorization (resource-wide)


I want to:

  • Control visibility of ExportAction and ImportAction using policy
  • Prevent execution if user is unauthorized
In my PostPolicy I have:

public function export(User $user): bool
{
    return $user->hasRole('admin');
}

public function import(User $user): bool
{
    return $user->hasRole('editor');
}


Then in my PostResource, I attach:

use Filament\Actions\ExportAction;
use Filament\Actions\ImportAction;

public static function table(Table $table): Table
{
    return $table
        ->headerActions([
            ExportAction::make()
                ->visible(fn () => auth()->user()->can('export', Post::class))
                ->authorize(fn () => auth()->user()->can('export', Post::class)),

            ImportAction::make()
                ->visible(fn () => auth()->user()->can('import', Post::class))
                ->authorize(fn () => auth()->user()->can('import', Post::class)),
        ]);
}


Is this the correct way? Or is there a more idiomatic "Filament way" to handle this?
Was this page helpful?