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
return Action::make('delete');
2. Defining the Deletion Logic and Sending a notification:
->action(function () {
$this->record->delete();
Notification::make()
->title('Record deleted')
->body('The record have been deleted successfully..')
->success()
->send();
//Redirecting the User
return redirect(ModelResource::getUrl());
})
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
return redirect(ModelResource::getUrl());
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
->requiresConfirmation()
5. Extending the Functionality
->color('warning')
->extraAttributes([
'class' => 'mx-auto my-1 w-full',
])
->modalHeading('Delete Record')
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:
{{ $this->deleteAction }}
The Code
public function deleteAction(): Action
{
return Action::make('delete')
->action(function () {
$this->record->delete();
Notification::make()
->title('Record deleted')
->body('The record have been deleted successfully..')
->success()
->send();
// Redirect after deletion
return redirect(ModelResource::getUrl());
})
->requiresConfirmation()
->color('warning')
->extraAttributes([
'class' => 'mx-auto my-1 w-full',
])
->modalHeading('Delete Record');
}