
Reuse action in both Table and Header
- Published: 17 Aug 2024 Updated: 17 Aug 2024
how to use an action as a headerAction or as a table row action without code duplication

With FilamentPHP, you can create an action and reuse it in multiple resources. Here is a quick example by @awcodes on how to create a reusable action.
But what if you need to reuse the same action in different places, such as in a header action and on a row table? This is not possible by default, as each one extends a different class.
Here’s how FilamentPHP handles this internally:
first, create a trait, Something like this:
1use Illuminate\Database\Eloquent\Model;
2
3trait HasDefaultAttributes
4{
5 public static function getDefaultName(): ?string
6 {
7 return 'create';
8 }
9
10 protected function setUp(): void
11 {
12 parent::setUp();
13
14 $this->action(function (): void {
15 //...
16 });
17 }
18}
Then create the header action:
and add the trait we just created:
1use Filament\Actions\Action;
2
3class EntityCreateAction extends Action
4{
5 use HasDefaultAttributes;
6}
and for the table row action:
1use Filament\Tables\Actions\Action;
2
3class EntityCreateAction extends Action
4{
5 use HasDefaultAttributes;
6}
This was originally shard by @leandrocfe.

Related Tricks:
Learn how to implement row-level security in Filament tables using the applyRowAccessPolicy macro that filters query results based on user permissions through Laravel's policy system.
make all Field or any components translatable
how to use a resource with multiple models