Creating records
Customizing data before saving
Sometimes, you may wish to modify form data before it is finally saved to the database. To do this, you may define a mutateFormDataBeforeCreate()
method on the Create page class, which accepts the $data
as an array, and returns the modified version:
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['user_id'] = auth()->id();
return $data;
}
Alternatively, if you're creating records in a modal action, check out the Actions documentation.
Customizing the creation process
You can tweak how the record is created using the handleRecordCreation()
method on the Create page class:
use Illuminate\Database\Eloquent\Model;
protected function handleRecordCreation(array $data): Model
{
return static::getModel()::create($data);
}
Alternatively, if you're creating records in a modal action, check out the Actions documentation.
Customizing redirects
By default, after saving the form, the user will be redirected to the Edit page of the resource, or the View page if it is present.
You may set up a custom redirect when the form is saved by overriding the getRedirectUrl()
method on the Create page class.
For example, the form can redirect back to the List page:
protected function getRedirectUrl(): string
{
return $this->getResource()::getUrl('index');
}
If you wish to be redirected to the previous page, else the index page:
protected function getRedirectUrl(): string
{
return $this->previousUrl ?? $this->getResource()::getUrl('index');
}
Customizing the save notification
When the record is successfully created, a notification is dispatched to the user, which indicates the success of their action.
To customize the title of this notification, define a getCreatedNotificationTitle()
method on the create page class:
protected function getCreatedNotificationTitle(): ?string
{
return 'User registered';
}
Alternatively, if you're creating records in a modal action, check out the Actions documentation.
You may customize the entire notification by overriding the getCreatedNotification()
method on the create page class:
use Filament\Notifications\Notification;
protected function getCreatedNotification(): ?Notification
{
return Notification::make()
->success()
->title('User registered')
->body('The user has been created successfully.');
}
To disable the notification altogether, return null
from the getCreatedNotification()
method on the create page class:
use Filament\Notifications\Notification;
protected function getCreatedNotification(): ?Notification
{
return null;
}
Lifecycle hooks
Hooks may be used to execute code at various points within a page's lifecycle, like before a form is saved. To set up a hook, create a protected method on the Create page class with the name of the hook:
protected function beforeCreate(): void
{
// ...
}