AmoyCreative

Read Time: 3 minutes |

Laravel Filament: Creating a Custom Action with Redirect in Filament

When building applications with Filament, it’s common to include features that allow users to use custom actions. After searching high and low I finally figured out how to create a custom action to delete a record on a filament page and redirect to the resource list. I have outlined my steps below.

1. Create the action

Actions in Filament allow you to define interactive elements such as buttons, modals, and forms that trigger specific functionality.

2. Defining the Deletion Logic and Sending a Notification:

Inside the  action callback, the  delete method is called on the current record. This removes the record from the database.  $this->record refers to the instance of the model being viewed or managed.

After the record is deleted, a notification is displayed to the user. This feedback confirms that the operation was successful:

  • title specifies the notification’s header.
  • body provides additional details about the action.
  • success sets the notification style to indicate a positive outcome.
  • send ensures the notification is displayed immediately.

3. Redirecting the User

This line redirects the user to the main page of the  ModelResource. Using  ModelResource::getUrl() ensures the URL is dynamically generated and adheres to the resource’s structure.

4. Adding Confirmation

This method prompts the user with a confirmation dialog before executing the action. It ensures that accidental deletions are avoided, especially for critical records.

5. Extending the Functionality

You can further enhance this action by adding colors, CSS and updating the modal heading.

  • color('warning') sets the button’s color to yellow, signalling caution to the user.
  • extraAttributes adds custom CSS classes for fine-tuned styling, ensuring the button is centered and spans the full width.
  • modalHeading('Delete Record') sets the heading of the confirmation modal to “Delete Record,” providing clarity about the action the user is about to perform.

Rendering the action on the custom page

In the Blade template, this delete action is rendered and displayed using the following snippet:

The Code