### Provide Example CSV Data with Multiple Example Rows Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Use the `examples()` method on an `ImportColumn` to provide multiple example values for a column in the example CSV. ```php use Filament\Actions\Imports\ImportColumn; ImportColumn::make('sku') ->examples(['ABC123', 'DEF456']) ``` -------------------------------- ### Provide Example CSV Data with a Single Example Row Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Use the `example()` method on an `ImportColumn` to provide a single example value for a column in the example CSV. ```php use Filament\Actions\Imports\ImportColumn; ImportColumn::make('sku') ->example('ABC123') ``` -------------------------------- ### Basic Export Action Setup Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Initialize the ExportAction and specify the custom exporter class to handle the export process. ```php use App\Filament\Exports\ProductExporter; use Filament\Actions\ExportAction; ExportAction::make() ->exporter(ProductExporter::class) ``` -------------------------------- ### Basic Create Action Setup Source: https://github.com/filamentphp/actions/blob/5.x/docs/04-create.md Use this to open a modal with a form for creating Eloquent records. Define the form schema using Filament's form components. ```php use Filament\Actions\CreateAction; use Filament\Forms\Components\TextInput; CreateAction::make() ->schema([ TextInput::make('title') ->required() ->maxLength(255), // ... ]) ``` -------------------------------- ### Configure All Export Disks Globally Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Set a default storage disk for all export actions by using `ExportAction::configureUsing()` in a service provider. This example sets the disk to 's3'. ```php use Filament\Actions\ExportAction; ExportAction::configureUsing(fn (ExportAction $action) => $action->fileDisk('s3')); ``` -------------------------------- ### Configure Export Filesystem Disk Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Specify a custom storage disk for exported files using the `fileDisk()` method on the action. This example sets the disk to 's3'. ```php use Filament\Actions\ExportAction; ExportAction::make() ->exporter(ProductExporter::class) ->fileDisk('s3') ``` -------------------------------- ### Customize Example CSV Header Per Column Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Use the `exampleHeader()` method on an `ImportColumn` to customize the header name for that specific column in the example CSV. ```php use Filament\Actions\Imports\ImportColumn; ImportColumn::make('sku') ->exampleHeader('SKU') ``` -------------------------------- ### Custom Rate Limiting on Action Mount Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Implement custom rate limiting logic within the `mountUsing()` method to control when the rate limit is checked, for example, when an action modal is opened. This example uses Laravel's RateLimiter to track attempts and send a custom notification. ```php use Filament\Actions\Action; use Filament\Notifications\Notification; use Illuminate\Support\Facades\RateLimiter; Action::make('delete') ->mountUsing(function () { if (RateLimiter::tooManyAttempts( $rateLimitKey = 'delete:' . auth()->id(), maxAttempts: 5, )) { Notification::make() ->title('Too many attempts') ->body('Please try again in ' . RateLimiter::availableIn($rateLimitKey) . ' seconds.') ->danger() ->send(); return; } RateLimiter::hit($rateLimitKey); }) ``` -------------------------------- ### Custom Rate Limiting on Action Execution Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Implement custom rate limiting logic within the `action()` method to control when the rate limit is checked, for example, when the action is actually executed. This example uses Laravel's RateLimiter to track attempts and send a custom notification before proceeding with the action's core logic. ```php use Filament\Actions\Action; use Filament\Notifications\Notification; use Illuminate\Support\Facades\RateLimiter; Action::make('delete') ->action(function () { if (RateLimiter::tooManyAttempts( $rateLimitKey = 'delete:' . auth()->id(), maxAttempts: 5, )) { Notification::make() ->title('Too many attempts') ->body('Please try again in ' . RateLimiter::availableIn($rateLimitKey) . ' seconds.') ->danger() ->send(); return; } RateLimiter::hit($rateLimitKey); // ... }) ``` -------------------------------- ### Force Delete Table Bulk Action Source: https://github.com/filamentphp/actions/blob/5.x/docs/09-force-delete.md Add a bulk action to your table to allow users to force-delete multiple selected records simultaneously. Requires `Filament ables able` setup. ```php use Filament\Actions\ForceDeleteBulkAction; use Filament\Tables\Table; public function table(Table $table): Table { return $table ->toolbarActions([ ForceDeleteBulkAction::make(), ]); } ``` -------------------------------- ### Modify Export Query with Options Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Inject `$options` into `modifyQueryUsing` to dynamically filter exports based on user-provided options. This example uses an 'isActive' option. ```php use App\Filament\Exports\ProductExporter; use Illuminate\Database\Eloquent\Builder; ExportAction::make() ->exporter(ProductExporter::class) ->modifyQueryUsing(fn (Builder $query, array $options) => $query->where('is_active', $options['isActive'] ?? true)) ``` -------------------------------- ### Customize Export File Name with Action Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Use the `fileName()` method on the action to customize the generated file name for exports. This example creates a name based on the export's key. ```php use Filament\Actions\ExportAction; use Filament\Actions\Exports\Models\Export; ExportAction::make() ->exporter(ProductExporter::class) ->fileName(fn (Export $export): string => "products-{$export->getKey()}") ``` -------------------------------- ### Change Slide-over Position Source: https://github.com/filamentphp/actions/blob/5.x/docs/02-modals.md Control the slide-over's entry point using `slideOverPosition()`. Pass `SlideOverPosition::Start` to make it slide in from the beginning of the screen, which is useful for actions near the viewport's start. ```php use Filament\Actions\Action; use Filament\Support\Enums\SlideOverPosition; Action::make('updateAuthor') ->schema([ // ... ]) ->action(function (array $data): void { // ... }) ->slideOver() ->slideOverPosition(SlideOverPosition::Start) ``` -------------------------------- ### Run JavaScript on Action Click Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use `actionJs()` for simple client-side interactions that do not require a network request. It provides `$get()` and `$set()` utilities for form field manipulation. Note: This method cannot perform server-side processing or open modals. ```php use Filament\Actions\Action; use Filament\Forms\Components\TextInput; TextInput::make('title') ->live(onBlur: true) ->afterContent( Action::make('generateSlug') ->actionJs(<<<'JS' $set('slug', $get('title').toLowerCase().replaceAll(' ', '-')) JS) ) TextInput::make('slug') ``` -------------------------------- ### Halt Replication Process in Filament Actions Source: https://github.com/filamentphp/actions/blob/5.x/docs/08-replicate.md Use `$action->halt()` inside a lifecycle hook to stop the entire replication process. This example shows how to halt replication if a user does not have an active subscription. ```php use App\Models\Post; use Filament\Actions\Action; use Filament\Actions\ReplicateAction; use Filament\Notifications\Notification; ReplicateAction::make() ->before(function (ReplicateAction $action, Post $record) { if (! $record->team->subscribed()) { Notification::make() ->warning() ->title('You don\'t have an active subscription!') ->body('Choose a plan to continue.') ->persistent() ->actions([ Action::make('subscribe') ->button() ->url(route('subscribe'), shouldOpenInNewTab: true), ]) ->send(); $action->halt(); } }) ``` -------------------------------- ### Filament Create Action Wizard Steps Source: https://github.com/filamentphp/actions/blob/5.x/docs/04-create.md Transform the creation process into a multi-step wizard by defining `steps()` instead of a `schema()`. Each step can have its own description and schema. ```php use Filament\Actions\CreateAction; use Filament\Forms\Components\MarkdownEditor; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Schemas\Components\Wizard\Step; CreateAction::make() ->steps([ Step::make('Name') ->description('Give the category a unique name') ->schema([ TextInput::make('name') ->required() ->live() ->afterStateUpdated(fn ($state, callable $set) => $set('slug', Str::slug($state))), TextInput::make('slug') ->disabled() ->required() ->unique(Category::class, 'slug'), ]) ->columns(2), Step::make('Description') ->description('Add some extra details') ->schema([ MarkdownEditor::make('description'), ]), Step::make('Visibility') ->description('Control who can view it') ->schema([ Toggle::make('is_visible') ->label('Visible to customers.') ->default(true), ]), ]) ``` -------------------------------- ### Modify Export Query with WHERE Clause Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Use `modifyQueryUsing` to filter the export query based on specific conditions. This example filters for active products. ```php use App\Filament\Exports\ProductExporter; use Filament\Actions\ExportAction; use Illuminate\Database\Eloquent\Builder; ExportAction::make() ->exporter(ProductExporter::class) ->modifyQueryUsing(fn (Builder $query) => $query->where('is_active', true)) ``` -------------------------------- ### Skippable Steps in Filament Wizard Source: https://github.com/filamentphp/actions/blob/5.x/docs/04-create.md Enable free navigation in a wizard by using the `skippableSteps()` method, allowing users to skip any step. ```php use Filament\Actions\CreateAction; CreateAction::make() ->steps([ // ... ]) ->skippableSteps() ``` -------------------------------- ### Initialize Replicate Action Source: https://github.com/filamentphp/actions/blob/5.x/docs/08-replicate.md Basic initialization of the ReplicateAction. This action is used to replicate Eloquent records. ```php use Filament\Actions\ReplicateAction; ReplicateAction::make() ``` -------------------------------- ### Configure Column Selection Layout Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Use `columnMappingColumns()` to set the number of columns for the column selection form on large screens. The layout remains responsive for smaller screens. ```php use App\Filament\Exports\ProductExporter; use Filament\Actions\ExportAction; ExportAction::make() ->exporter(ProductExporter::class) ->columnMappingColumns(3) ``` -------------------------------- ### Create a Simple Action Group Source: https://github.com/filamentphp/actions/blob/5.x/docs/03-grouping-actions.md Use `ActionGroup::make()` to group multiple actions like view, edit, and delete into a single dropdown. ```php use Filament\Actions\Action; use Filament\Actions\ActionGroup; ActionGroup::make([ Action::make('view'), Action::make('edit'), Action::make('delete'), ]) ``` -------------------------------- ### Execute Code Before and After Restore Source: https://github.com/filamentphp/actions/blob/5.x/docs/10-restore.md Utilize the before() and after() methods to run custom logic immediately before or after a record is restored. ```php use Filament\Actions\RestoreAction; RestoreAction::make() ->before(function () { // ... }) ->after(function () { // ... }) ``` -------------------------------- ### Override Exporter's getFileDisk Method Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Override the `getFileDisk` method within an exporter class to specify the storage disk for all exports using that exporter. This example returns 's3'. ```php public function getFileDisk(): string { return 's3'; } ``` -------------------------------- ### Initialize Restore Action Source: https://github.com/filamentphp/actions/blob/5.x/docs/10-restore.md Use this to add a restore action to your Filament components. It prompts the user for confirmation in a modal before restoring. ```php use Filament\Actions\RestoreAction; RestoreAction::make() ``` -------------------------------- ### Execute Code on Modal Mount Source: https://github.com/filamentphp/actions/blob/5.x/docs/02-modals.md Use `mountUsing()` to run custom code when a modal opens. This is often used to initialize or fill the form within the modal. Remember to call `$form->fill()` if overriding the default initialization. ```php use Filament\Actions\Action; use Filament\Schemas\Schema; Action::make('create') ->mountUsing(function (Schema $form) { $form->fill(); // ... }) ``` -------------------------------- ### Customize Export Job Middleware Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Override the getJobMiddleware method to apply custom middleware to export jobs, such as WithoutOverlapping to prevent concurrent processing. The example shows setting an expiration time for the lock. ```php use Illuminate\Queue\Middleware\WithoutOverlapping; public function getJobMiddleware(): array { return [ (new WithoutOverlapping("export{$this->export->getKey()}"))->expireAfter(600), ]; } ``` -------------------------------- ### Responsive Icon Button Trigger Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use `labeledFrom()` to make an action display a label on larger screens and transform into an icon button on smaller screens. Pass the responsive breakpoint as an argument. ```php use Filament\Actions\Action; Action::make('edit') ->icon('heroicon-m-pencil-square') ->button() ->labeledFrom('md') ``` -------------------------------- ### Publish Filament Actions Migrations Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Publish and run migrations for job batches, notifications, and Filament's export-related tables. ```bash php artisan make:queue-batches-table php artisan make:notifications-table php artisan vendor:publish --tag=filament-actions-migrations php artisan migrate ``` -------------------------------- ### Override Exporter's modifyQuery Method Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Override the `modifyQuery` method within an exporter class to apply query modifications universally for that exporter. This example includes eager loading with conditional relations. ```php use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\MorphTo; public static function modifyQuery(Builder $query): Builder { return $query->with([ 'purchasable' => fn (MorphTo $morphTo) => $morphTo->morphWith([ ProductPurchase::class => ['product'], ServicePurchase::class => ['service'], Subscription::class => ['plan'], ]), ]); } ``` -------------------------------- ### Implement Export Policy View Method Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Implement the `view()` method in your `ExportPolicy` to define custom authorization logic for accessing export downloads. Ensure to include logic for the original user if needed. ```php use App\Models\User; use Filament\Actions\Exports\Models\Export; public function view(User $user, Export $export): bool { return $export->user()->is($user); } ``` -------------------------------- ### Custom State Casting for Import Column Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Use `castStateUsing()` to define custom logic for casting CSV data before validation. This example removes non-numeric characters, casts to float, and rounds to two decimal places. ```php use Filament\Actions\Imports\ImportColumn; ImportColumn::make('price') ->castStateUsing(function (string $state): ?float { if (blank($state)) { return null; } $state = preg_replace('/[^0-9.]/', '', $state); $state = floatval($state); return round($state, precision: 2); }) ``` -------------------------------- ### Basic ImportAction Usage Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Instantiate the `ImportAction` and specify the custom importer class responsible for handling the import logic. ```php use App\Filament\Imports\ProductImporter; use Filament\Actions\ImportAction; ImportAction::make() ->importer(ProductImporter::class) ``` -------------------------------- ### Override Exporter's getFileName Method Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Override the `getFileName` method within an exporter class to define a custom file name for all exports using that exporter. This example generates a name based on the export's key. ```php use Filament\Actions\Exports\Models\Export; public function getFileName(Export $export): string { return "products-{$export->getKey()}"; } ``` -------------------------------- ### Render Wizard in Modal Source: https://github.com/filamentphp/actions/blob/5.x/docs/02-modals.md Create a multi-step form wizard within a modal by using the `steps()` method instead of `schema()`. Each step can have its own description and schema. ```php use Filament\Actions\Action; use Filament\Forms\Components\MarkdownEditor; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Schemas\Components\Wizard\Step; Action::make('create') ->steps([ Step::make('Name') ->description('Give the category a unique name') ->schema([ TextInput::make('name') ->required() ->live() ->afterStateUpdated(fn ($state, callable $set) => $set('slug', Str::slug($state))), TextInput::make('slug') ->disabled() ->required() ->unique(Category::class, 'slug'), ]) ->columns(2), Step::make('Description') ->description('Add some extra details') ->schema([ MarkdownEditor::make('description'), ]), Step::make('Visibility') ->description('Control who can view it') ->schema([ Toggle::make('is_visible') ->label('Visible to customers.') ->default(true), ]), ]) ``` -------------------------------- ### Update Existing Records by SKU Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Customize `resolveRecord` to use `firstOrNew` and match records by a specific column, such as 'sku', to update existing products. ```php use App\Models\Product; public function resolveRecord(): ?Product { return Product::firstOrNew([ 'sku' => $this->data['sku'], ]); } ``` -------------------------------- ### Custom XLSX Row Creation with Cell Styling Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Override `makeXlsxRow()` to create custom `Cell` objects for individual styling within an XLSX row. This example demonstrates conditional styling for 'name' and 'price' columns using `StyleMerger` and `Cell` objects. Imports for `Cell`, `Row`, `Style`, and `StyleMerger` are required. ```php use OpenSpout\Common\Entity\Cell; use OpenSpout\Common\Entity\Row; use OpenSpout\Common\Entity\Style\Style; use OpenSpout\Writer\Common\Manager\Style\StyleMerger; /** * @param array $values */ public function makeXlsxRow(array $values, ?Style $style = null): Row { $styleMerger = new StyleMerger(); $cells = []; foreach (array_keys($this->columnMap) as $columnIndex => $column) { $cells[] = match ($column) { 'name' => Cell::fromValue( $values[$columnIndex], $styleMerger->merge( (new Style())->setFontUnderline(), $style, ), ), 'price' => Cell::fromValue( $values[$columnIndex], (new Style())->setFontSize(12), ), default => Cell::fromValue($values[$columnIndex]), }, } return new Row($cells, $style); } ``` -------------------------------- ### Generate Importer with Columns Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Use the `--generate` flag with the `make:filament-importer` command to automatically create import columns based on the model's database schema. ```bash php artisan make:filament-importer Product --generate ``` -------------------------------- ### Render List of Actions in Schema Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Wrap multiple actions in the `Actions` layout component to render them on their own row. Actions can have icons and custom colors. ```php use Filament\Actions\Action; use Filament\Schemas\Components\Actions; Actions::make([ Action::make('star') ->icon('heroicon-m-star'), Action::make('resetStars') ->icon('heroicon-m-x-mark') ->color('danger'), ]) ``` -------------------------------- ### Improve Restore Bulk Action Performance with Single Query Source: https://github.com/filamentphp/actions/blob/5.x/docs/10-restore.md If individual record authorization and model events are not required, use fetchSelectedRecords(false) to restore records in a single database query, minimizing memory overhead. ```php use Filament\Actions\RestoreBulkAction; RestoreBulkAction::make() ->fetchSelectedRecords(false) ``` -------------------------------- ### Available Importer Lifecycle Hooks Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md This class demonstrates various lifecycle hooks available for importers, allowing custom actions at different stages of data processing and saving. ```php use Filament\Actions\Imports\Importer; class ProductImporter extends Importer { // ... protected function beforeValidate(): void { // Runs before the CSV data for a row is validated. } protected function afterValidate(): void { // Runs after the CSV data for a row is validated. } protected function beforeFill(): void { // Runs before the validated CSV data for a row is filled into a model instance. } protected function afterFill(): void { // Runs after the validated CSV data for a row is filled into a model instance. } protected function beforeSave(): void { // Runs before a record is saved to the database. } protected function beforeCreate(): void { // Similar to `beforeSave()`, but only runs when creating a new record. } protected function beforeUpdate(): void { // Similar to `beforeSave()`, but only runs when updating an existing record. } protected function afterSave(): void { // Runs after a record is saved to the database. } protected function afterCreate(): void { // Similar to `afterSave()`, but only runs when creating a new record. } protected function afterUpdate(): void { // Similar to `afterSave()`, but only runs when updating an existing record. } } ``` -------------------------------- ### Create Filament Importer Class Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Generate a new importer class for a specific model using the `make:filament-importer` Artisan command. ```bash php artisan make:filament-importer Product ``` -------------------------------- ### Combine Injected Utilities Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Dynamically combine multiple utility parameters within a single function, such as arguments and the Livewire component instance. ```php use Livewire\Component; function (array $arguments, Component $livewire) { // ... } ``` -------------------------------- ### Define Export Options Form Components Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Return form components from `getOptionsFormComponents()` to allow users to customize export behavior, such as limiting column content length. ```php use Filament\Forms\Components\TextInput; public static function getOptionsFormComponents(): array { return [ TextInput::make('descriptionLimit') ->label('Limit the length of the description column content') ->integer(), ]; } ``` -------------------------------- ### Customize Record Creation Process Source: https://github.com/filamentphp/actions/blob/5.x/docs/04-create.md Override the default record creation logic with the `using()` method. This method receives the data and model class name, and should return the created Eloquent model. ```php use Filament\Actions\CreateAction; use Illuminate\Database\Eloquent\Model; CreateAction::make() ->using(function (array $data, string $model): Model { return $model::create($data); }) ``` -------------------------------- ### Improve Restore Bulk Action Performance with Chunking Source: https://github.com/filamentphp/actions/blob/5.x/docs/10-restore.md For large numbers of records, use chunkSelectedRecords() to reduce memory usage by fetching and restoring records in smaller batches. ```php use Filament\Actions\RestoreBulkAction; RestoreBulkAction::make() ->chunkSelectedRecords(250) ``` -------------------------------- ### Replicate Action Lifecycle Hooks Source: https://github.com/filamentphp/actions/blob/5.x/docs/08-replicate.md Utilize lifecycle hooks like `before()`, `beforeReplicaSaved()`, and `after()` to execute custom logic at different stages of the replication process. These hooks can inject utilities like the replica model. ```php use Filament\Actions\ReplicateAction; use Illuminate\Database\Eloquent\Model; ReplicateAction::make() ->before(function () { // Runs before the record has been replicated. }) ->beforeReplicaSaved(function (Model $replica): void { // Runs after the record has been replicated but before it is saved to the database. }) ->after(function (Model $replica): void { // Runs after the replica has been saved to the database. }) ``` -------------------------------- ### Use Import Options in resolveRecord Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Access imported options via `$this->options` within the `resolveRecord` method to conditionally update existing records based on user-selected import settings. ```php use App\Models\Product; public function resolveRecord(): ?Product { if ($this->options['updateExisting'] ?? false) { return Product::firstOrNew([ 'sku' => $this->data['sku'], ]); } return new Product(); } ``` -------------------------------- ### Basic Delete Action with Confirmation Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use this action to perform a delete operation that requires user confirmation before execution. It's suitable for destructive actions. ```php use Filament\Actions\Action; Action::make('delete') ->requiresConfirmation() ->action(fn () => $this->client->delete()) ``` -------------------------------- ### Set Static Export Options Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Pass a set of static options to the export action using the `options()` method for predefined export configurations. ```php use App\Filament\Exports\ProductExporter; use Filament\Actions\ExportAction; ExportAction::make() ->exporter(ProductExporter::class) ->options([ 'descriptionLimit' => 250, ]) ``` -------------------------------- ### Optimize Modal Configuration Source: https://github.com/filamentphp/actions/blob/5.x/docs/02-modals.md Use the `modal()` method to inform Filament that a modal exists for an action, preventing redundant checks and potential re-execution of heavy operations within configuration methods. ```php use Filament\Actions\Action; Action::make('updateAuthor') ->modal() ``` -------------------------------- ### Optimize Bulk Force Delete Performance (No Fetch) Source: https://github.com/filamentphp/actions/blob/5.x/docs/09-force-delete.md If individual record authorization and model events are not required, use `fetchSelectedRecords(false)` to delete records in a single query, bypassing memory loading. ```php use Filament\Actions\ForceDeleteBulkAction; ForceDeleteBulkAction::make() ->fetchSelectedRecords(false) ``` -------------------------------- ### Register Keybindings for Actions Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Attach keyboard shortcuts to trigger buttons using Mousetrap key codes. The `keyBindings()` method accepts an array of key combinations. ```php use Filament\Actions\Action; Action::make('save') ->action(fn () => $this->save()) ->keyBindings(['command+s', 'ctrl+s']) ``` -------------------------------- ### Authorize Action Using Policy Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use the `authorize()` method to specify a policy method for authorization. Filament uses the current Eloquent model for the action. ```php use Filament\Actions\Action; Action::make('edit') ->url(fn (): string => route('posts.edit', ['post' => $this->post])) ->authorize('update') ``` -------------------------------- ### Optimize Bulk Force Delete Performance (Chunking) Source: https://github.com/filamentphp/actions/blob/5.x/docs/09-force-delete.md For large datasets, use `chunkSelectedRecords()` to reduce memory usage by processing records in smaller batches. Specify the batch size as an argument. ```php use Filament\Actions\ForceDeleteBulkAction; ForceDeleteBulkAction::make() ->chunkSelectedRecords(250) ``` -------------------------------- ### Full Width Actions in Schema Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Make a list of actions span the full width of the schema by calling the `fullWidth()` method on the `Actions` component. ```php use Filament\Actions\Action; use Filament\Schemas\Components\Actions; Actions::make([ Action::make('star') ->icon('heroicon-m-star'), Action::make('resetStars') ->icon('heroicon-m-x-mark') ->color('danger'), ])->fullWidth() ``` -------------------------------- ### Limit Column Length Using Export Options Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Use the `limit()` method with a closure that accesses `$options` to dynamically set the maximum length for column content. ```php use Filament\Actions\Exports\ExportColumn; ExportColumn::make('description') ->limit(fn (array $options): int => $options['descriptionLimit'] ?? 100) ``` -------------------------------- ### Set XLSX Column Widths Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Pass options to the OpenSpout XLSX Writer to set column widths. This method should return an instance of OpenSpout\Writer\XLSX\Options. ```php use OpenSpout\Writer\XLSX\Options; public function getXlsxWriterOptions(): ?Options { $options = new Options(); $options->setColumnWidth(10, 1); $options->setColumnWidthForRange(12, 2, 3); return $options; } ``` -------------------------------- ### Adding Helper Text to Import Columns Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Provide additional guidance to users by adding `helperText()` to an import column, which appears below the mapping select. ```php use Filament\Actions\Imports\ImportColumn; ImportColumn::make('skus') ->multiple(',') ->helperText('A comma-separated list of SKUs.') ``` -------------------------------- ### Action Authorization with Tooltip Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use `authorizationTooltip()` to disable an action and show a tooltip with the policy response message when unauthorized. Fallback messages can be provided with `authorizationMessage()`. ```php use Filament\Actions\Action; Action::make('edit') ->url(fn (): string => route('posts.edit', ['post' => $this->post])) ->authorize('update') ->authorizationTooltip() ``` -------------------------------- ### Optimize Bulk Delete Performance (Chunking) Source: https://github.com/filamentphp/actions/blob/5.x/docs/07-delete.md Improve memory usage for large-scale deletions by using `chunkSelectedRecords()` to process records in smaller batches. ```php use Filament\Actions\DeleteBulkAction; DeleteBulkAction::make() ->chunkSelectedRecords(250) ``` -------------------------------- ### Configure Polymorphic User Relationship Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Replace the `user_id` column with `morphs('user')` and call `Import::polymorphicUserRelationship()` in a service provider's `boot()` method to enable polymorphic user associations. ```php $table->morphs('user'); ``` ```php use Filament\Actions\Imports\Models\Import; Import::polymorphicUserRelationship(); ``` -------------------------------- ### Format Column State Using Export Options Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Access `$options` within `formatStateUsing()` to dynamically format column data based on user-defined or static export settings. ```php use Filament\Actions\Exports\ExportColumn; ExportColumn::make('description') ->formatStateUsing(function (string $state, array $options): string { return (string) str($state)->limit($options['descriptionLimit'] ?? 100); }) ``` -------------------------------- ### Render Action Group as Button Group Source: https://github.com/filamentphp/actions/blob/5.x/docs/03-grouping-actions.md Use the `buttonGroup()` method to render the action group as a series of distinct buttons instead of a dropdown. This is useful for actions that should be immediately accessible. ```php use Filament\Actions\Action; use Filament\Actions\ActionGroup; use Filament\Support\Icons\Heroicon; ActionGroup::make([ Action::make('edit') ->color('gray') ->icon(Heroicon::PencilSquare) ->hiddenLabel(), Action::make('delete') ->color('gray') ->icon(Heroicon::Trash) ->hiddenLabel(), ]) ->buttonGroup() ``` -------------------------------- ### Conditionally Show Action Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use the `visible()` method to show an action only if the condition is true. This is useful for authorization. ```php use Filament\Actions\Action; Action::make('edit') ->url(fn (): string => route('posts.edit', ['post' => $this->post])) ->visible(auth()->user()->can('update', $this->post)) ``` -------------------------------- ### Set Static Import Options Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Alternatively, set static options directly on the `ImportAction` using the `options()` method, which can then be accessed within the importer class. ```php use App\Filament\Imports\ProductImporter; use Filament\Actions\ImportAction; ImportAction::make() ->importer(ProductImporter::class) ->options([ 'updateExisting' => true, ]) ``` -------------------------------- ### Enable Automatic Dropdown Placement Source: https://github.com/filamentphp/actions/blob/5.x/docs/03-grouping-actions.md Allow the dropdown to automatically position itself based on available space using the `dropdownAutoPlacement()` method. ```php use Filament\Actions\ActionGroup; ActionGroup::make([ // Array of actions ]) ->dropdownAutoPlacement() ``` -------------------------------- ### Badge Trigger Style Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use the `badge()` method to style an action as a badge. This style includes a background color, label, and can optionally feature an icon. ```php use Filament\Actions\Action; Action::make('edit') ->badge() ``` -------------------------------- ### Generate Exporter Class with Column Generation Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Automatically generate exporter columns based on the model's database columns during exporter class creation. ```bash php artisan make:filament-exporter Product --generate ``` -------------------------------- ### Open Action as Slide-over Source: https://github.com/filamentphp/actions/blob/5.x/docs/02-modals.md Use the `slideOver()` method to open an action as a slide-over dialog instead of a traditional modal. The content will span the full height of the browser. ```php use Filament\Actions\Action; Action::make('updateAuthor') ->schema([ // ... ]) ->action(function (array $data): void { // ... }) ->slideOver() ``` -------------------------------- ### Bind Custom Import Job Class Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Replace the default `Filament Actions Imports Jobs ImportCsv` class with your custom implementation by binding it in a service provider's `register()` method. ```php use App\Jobs\ImportCsv; use Filament\Actions\Imports\Jobs\ImportCsv as BaseImportCsv; $this->app->bind(BaseImportCsv::class, ImportCsv::class); ``` -------------------------------- ### Access Livewire Component Instance Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Inject the current Livewire component instance into an action's function by defining a `$livewire` parameter. ```php use Livewire\Component; function (Component $livewire) { // ... } ``` -------------------------------- ### Customize Modal Content Alignment Source: https://github.com/filamentphp/actions/blob/5.x/docs/02-modals.md Use `modalAlignment()` to set content alignment to `Alignment::Start` or `Alignment::Center`. This method accepts a function for dynamic calculation. ```php use Filament\Actions\Action; use Filament\Support\Enums\Alignment; Action::make('updateAuthor') ->schema([ // ... ]) ->action(function (array $data): void { // ... }) ->modalAlignment(Alignment::Center) ``` -------------------------------- ### Add Restore Bulk Action to Table Source: https://github.com/filamentphp/actions/blob/5.x/docs/10-restore.md Integrate the RestoreBulkAction into your Filament table's toolbar to allow users to restore multiple selected records. ```php use Filament\Actions\RestoreBulkAction; use Filament\Tables\Table; public function table(Table $table): Table { return $table ->toolbarActions([ RestoreBulkAction::make(), ]); } ``` -------------------------------- ### Add Export Bulk Action to Table Toolbar Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Implement the ExportBulkAction as a toolbar action to allow users to select specific rows for export. ```php use App\Filament\Exports\ProductExporter; use Filament\Actions\ExportBulkAction; use Filament\Tables\Table; public function table(Table $table): Table { return $table ->toolbarActions([ ExportBulkAction::make() ->exporter(ProductExporter::class), ]); } ``` -------------------------------- ### Link Trigger Style Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use the `link()` method to style an action as a link. This style has no background color and appears as a link embedded within text, optionally including an icon. ```php use Filament\Actions\Action; Action::make('edit') ->link() ``` -------------------------------- ### Action Redirecting to a URL Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use this action to redirect the user to a specific URL when the button is clicked. The URL can be dynamically generated using a closure. ```php use Filament\Actions\Action; Action::make('edit') ->url(fn (): string => route('posts.edit', ['post' => $this->post])) ``` -------------------------------- ### Basic Rate Limiting for Actions Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Apply a rate limit to an action, restricting it to a maximum number of attempts per minute. The action will not run if the limit is exceeded, and a default notification will be shown. ```php use Filament\Actions\Action; Action::make('delete') ->rateLimit(5) ``` -------------------------------- ### Lifecycle Hooks for Force Delete Source: https://github.com/filamentphp/actions/blob/5.x/docs/09-force-delete.md Execute custom logic before or after a record is force-deleted using the `before()` and `after()` methods. These methods accept closures that can inject utilities. ```php use Filament\Actions\ForceDeleteAction; ForceDeleteAction::make() ->before(function () { // ... }) ->after(function () { // ... }) ``` -------------------------------- ### Optimize Bulk Delete Performance (Single Query) Source: https://github.com/filamentphp/actions/blob/5.x/docs/07-delete.md For maximum performance when individual record authorization and model events are not required, use `fetchSelectedRecords(false)` to delete records in a single query. ```php use Filament\Actions\DeleteBulkAction; DeleteBulkAction::make() ->fetchSelectedRecords(false) ``` -------------------------------- ### Set Action Button Size Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Control the size of the action button trigger using the `size()` method. Available options include `Size::Small`, `Size::Medium`, and `Size::Large`. A callable can be used for dynamic sizing. ```php use Filament\Actions\Action; use Filament\Support\Enums\Size; Action::make('create') ->size(Size::Large) ``` -------------------------------- ### Improve Column Mapping Guesses Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Enhance Filament's automatic column mapping by providing additional potential names for a column using the `guess()` method, improving accuracy for user-defined mappings. ```php use Filament\Actions\Imports\ImportColumn; ImportColumn::make('sku') ->guess(['id', 'number', 'stock-keeping unit']) ``` -------------------------------- ### Default XLSX Row Creation Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md The default implementation of `makeXlsxRow()` uses `Row::fromValues()` to create a row with an optional style. Imports for `Row` and `Style` are needed. ```php use OpenSpout\Common\Entity\Row; use OpenSpout\Common\Entity\Style\Style; /** * @param array $values */ public function makeXlsxRow(array $values, ?Style $style = null): Row { return Row::fromValues($values, $style); } ``` -------------------------------- ### Customizing Record Filling Logic Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Implement custom logic for how column data is applied to a record using the `fillRecordUsing()` method. This allows for transformations before saving. ```php use App\Models\Product; use Filament\Actions\Imports\ImportColumn; ImportColumn::make('sku') ->fillRecordUsing(function (Product $record, string $state): void { $record->sku = strtoupper($state); }) ``` -------------------------------- ### Halting the Filament Create Action Process Source: https://github.com/filamentphp/actions/blob/5.x/docs/04-create.md Halt the entire creation process by calling `$action->halt()` within a lifecycle hook. This prevents further execution and saving. ```php use App\Models\Post; use Filament\Actions\Action; use Filament\Actions\CreateAction; use Filament\Notifications\Notification; CreateAction::make() ->before(function (CreateAction $action, Post $record) { if (! $record->team->subscribed()) { Notification::make() ->warning() ->title('You don\'t have an active subscription!') ->body('Choose a plan to continue.') ->persistent() ->actions([ Action::make('subscribe') ->button() ->url(route('subscribe'), shouldOpenInNewTab: true), ]) ->send(); $action->halt(); } }) ``` -------------------------------- ### Filament Create Action Lifecycle Hooks Source: https://github.com/filamentphp/actions/blob/5.x/docs/04-create.md Use these hooks to execute code at various stages of the action's lifecycle, such as before or after form population, validation, or saving. ```php use Filament\Actions\CreateAction; CreateAction::make() ->beforeFormFilled(function () { // Runs before the form fields are populated with their default values. }) ->afterFormFilled(function () { // Runs after the form fields are populated with their default values. }) ->beforeFormValidated(function () { // Runs before the form fields are validated when the form is submitted. }) ->afterFormValidated(function () { // Runs after the form fields are validated when the form is submitted. }) ->before(function () { // Runs before the form fields are saved to the database. }) ->after(function () { // Runs after the form fields are saved to the database. }) ``` -------------------------------- ### Resolve Relationship Using Multiple Columns (OR) Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Provide an array of column names to `resolveUsing` to attempt resolution in an 'or' fashion. ```php use Filament\Actions\u001B[0m\u001B[1;38;5;208m\Imports\u001B[0m\u001B[1;38;5;112mImportColumn\u001B[0m; ImportColumn::make('author') ->relationship(resolveUsing: ['email', 'username']) ``` -------------------------------- ### Render Form in Modal and Access Data Source: https://github.com/filamentphp/actions/blob/5.x/docs/02-modals.md Create action modal forms using form components. The submitted form data is available in the `$data` array within the `action()` closure. ```php use App\Models\Post; use App\Models\User; use Filament\Actions\Action; use Filament\Forms\Components\Select; Action::make('updateAuthor') ->schema([ Select::make('authorId') ->label('Author') ->options(User::query()->pluck('name', 'id')) ->required(), ]) ->action(function (array $data, Post $record): void { $record->author()->associate($data['authorId']); $record->save(); }) ``` -------------------------------- ### Set Button Icon Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use the `icon()` method to add an icon to an action button. The icon can be a static string or a function for dynamic calculation. ```php use Filament\Actions\Action; Action::make('edit') ->url(fn (): string => route('posts.edit', ['post' => $this->post])) ->icon('heroicon-m-pencil-square') ``` -------------------------------- ### Configure Custom User Model for Exports Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Bind a custom `Authenticatable` model to the container in a service provider's `register()` method if not using the default `App\Models\User`. ```php use App\Models\Admin; use Illuminate\Contracts\Auth\Authenticatable; $this->app->bind(Authenticatable::class, Admin::class); ``` -------------------------------- ### Customizing the 'Create Another' Action Source: https://github.com/filamentphp/actions/blob/5.x/docs/04-create.md Modify the 'create another' action using `createAnotherAction()`, allowing customization of its label and other properties. ```php use Filament\Actions\CreateAction; use Filament\Actions\Action; CreateAction::make() ->createAnotherAction(fn (Action $action): Action => $action->label('Custom create another label')) ``` -------------------------------- ### Import BelongsTo Relationship Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Use the `relationship()` method to import data into a `BelongsTo` relationship. The column should contain the primary keys of the related records. ```php use Filament\Actions\Imports\ImportColumn; ImportColumn::make('author') ->relationship() ``` -------------------------------- ### Basic Edit Action with Form Schema Source: https://github.com/filamentphp/actions/blob/5.x/docs/05-edit.md Use this to create a basic edit action with a defined form schema for editing records. ```php use Filament\Actions\EditAction; use Filament\Forms\Components\TextInput; EditAction::make() ->schema([ TextInput::make('title') ->required() ->maxLength(255), // ... ]) ``` -------------------------------- ### Access Action Instance Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Inject the current action instance into an action's function by defining an `$action` parameter. ```php use Filament\Actions\Action; function (Action $action) { // ... } ``` -------------------------------- ### Enable Polymorphic User Relationship for Exports Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Swap the default `user()` relationship to a `MorphTo` relationship by calling `Export::polymorphicUserRelationship()` in a service provider's `boot()` method. ```php use Filament\Actions\Exports\Models\Export; Export::polymorphicUserRelationship(); ``` -------------------------------- ### Action Authorization with Notification Source: https://github.com/filamentphp/actions/blob/5.x/docs/01-overview.md Use `authorizationNotification()` to allow an action to remain clickable but send a notification with the policy response message when unauthorized. Fallback messages can be provided with `authorizationMessage()`. ```php use Filament\Actions\Action; Action::make('edit') ->url(fn (): string => route('posts.edit', ['post' => $this->post])) ->authorize('update') ->authorizationNotification() ``` -------------------------------- ### Lifecycle Hooks for Deletion Source: https://github.com/filamentphp/actions/blob/5.x/docs/07-delete.md Execute custom logic before or after a record is deleted by utilizing the `before()` and `after()` methods on the DeleteAction. ```php use Filament\Actions\DeleteAction; DeleteAction::make() ->before(function () { // ... }) ->after(function () { // ... }) ``` -------------------------------- ### Set CSV Header Offset in Filament Import Action Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Use `headerOffset()` to specify the number of rows to skip before the CSV header. This is useful when headers are not on the first row. ```php use App\Filament\Imports\ProductImporter; use Filament\Actions\ImportAction; ImportAction::make() ->importer(ProductImporter::class) ->headerOffset(5) ``` -------------------------------- ### Default Record Resolution in Importer Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md The default `resolveRecord` method creates a new model instance for each row. Uncomment the `firstOrNew` line to enable updating existing records. ```php use App\Models\Product; public function resolveRecord(): ?Product { // return Product::firstOrNew([ // // Update existing records, matching them by `$this->data['column_name']` // 'email' => $this->data['email'], // ]); return new Product(); } ``` -------------------------------- ### Define a beforeSave Lifecycle Hook Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Implement the `beforeSave` method to run custom logic before a validated row is saved to the database. ```php protected function beforeSave(): void { // ... } ``` -------------------------------- ### Customize Saving Process Source: https://github.com/filamentphp/actions/blob/5.x/docs/05-edit.md Override the default saving mechanism using the `using()` method to implement custom update logic for the record. ```php use Filament\Actions\EditAction; use Illuminate\Database\Eloquent\Model; EditAction::make() ->using(function (Model $record, array $data): Model { $record->update($data); return $record; }) ``` -------------------------------- ### Require Confirmation for Action Source: https://github.com/filamentphp/actions/blob/5.x/docs/02-modals.md Use `requiresConfirmation()` to add a confirmation modal before an action is executed. This is ideal for destructive actions. ```php use App\Models\Post; use Filament\Actions\Action; Action::make('delete') ->action(fn (Post $record) => $record->delete()) ->requiresConfirmation() ``` -------------------------------- ### Customize Import Job Batch Name Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Implement `getJobBatchName()` to set a custom name for job batches, aiding in organization and identification. ```php public function getJobBatchName(): ?string { return 'product-import'; } ``` -------------------------------- ### Set Custom Success Redirect URL Source: https://github.com/filamentphp/actions/blob/5.x/docs/05-edit.md Define a static URL to redirect to after a successful save using `successRedirectUrl()`. Ensure the route exists. ```php use Filament\Actions\EditAction; EditAction::make() ->successRedirectUrl(route('posts.list')) ``` -------------------------------- ### Customize Import Job Middleware Source: https://github.com/filamentphp/actions/blob/5.x/docs/11-import.md Override the `getJobMiddleware()` method in your importer class to define custom middleware for its jobs, such as `WithoutOverlapping` to prevent concurrent processing. ```php use Illuminate\Queue\Middleware\WithoutOverlapping; public function getJobMiddleware(): array { return [ (new WithoutOverlapping("import{$this->import->getKey()}"))->expireAfter(600), ]; } ``` -------------------------------- ### Customize Export Job Backoff Strategy Source: https://github.com/filamentphp/actions/blob/5.x/docs/12-export.md Override `getJobBackoff()` to define the waiting periods between job retries. This prevents overloading the server with failing jobs. ```php /** * @return int | array | null */ public function getJobBackoff(): int | array | null { return [60, 120, 300, 600]; } ```