The Filament Hook You Needed Was Already There: mutateFormDataBeforeCreate and Friends

Filament mutateFormDataBeforeCreate, beforeCreate, handleRecordCreation and afterCreate in v5: the real hook order, the transaction trap, and hook vs observer.

Steven Richardson
Steven Richardson
· 11 min read

A user_id that needs to come from the session. A toggle that exists only in the form and must never reach the insert. An order created through a service rather than Model::create(). A confirmation email that fires from the admin panel but not from the nightly importer. So you override save() on the Edit page, copy a chunk of Filament's internals to make it work, and it breaks on the next minor release. Filament v5 already exposes mutateFormDataBeforeCreate() and five siblings that do exactly this — the problem is that they're documented across three pages and nobody tells you the order they run in.

Map the order mutateFormDataBeforeCreate actually runs in#

Read CreateRecord::create() and EditRecord::save() in the Filament source and the order stops being folklore. Create and edit are not symmetrical, which is the single most useful thing to know before you pick a hook.

On the Create page, in order:

# Hook Signature What it's for
1 beforeFill() (): void Before defaults populate the form
2 afterFill() (): void After defaults populate the form
3 beforeValidate() (): void Before the submitted form validates
4 afterValidate() (): void After validation passes
5 mutateFormDataBeforeCreate() (array $data): array Reshape the array
6 beforeCreate() (): void Last chance to guard or halt
7 handleRecordCreation() (array $data): Model Persist the record
8 afterCreate() (): void Side effects, with $this->record available

On the Edit page the data hook and the guard hook swap places:

# Hook Signature What it's for
1 beforeFill() (): void Before the record hydrates the form
2 mutateFormDataBeforeFill() (array $data): array Reshape attributes on the way in
3 afterFill() (): void After the form is filled
4 beforeValidate() / afterValidate() (): void Around validation
5 beforeSave() (): void Guard — runs before the mutate hook
6 mutateFormDataBeforeSave() (array $data): array Reshape the array
7 handleRecordUpdate() (Model $record, array $data): Model Persist
8 afterSave() (): void Side effects

That inversion at steps 5 and 6 catches people out. On create, beforeCreate() runs after your data has been reshaped; on edit, beforeSave() runs before. If a guard needs to inspect the final payload, it belongs inside the mutate method on the edit page, not in beforeSave().

Hooks are plain protected methods — you define the ones you need and ignore the rest. If your create flow is a multi-step wizard, the same hooks fire: the wizard changes how the form is presented, not how the page saves.

Shape the data with mutateFormDataBeforeCreate#

mutateFormDataBeforeCreate() receives the validated form state as an array and returns the array you want persisted. Three jobs cover almost every use: stamping server-side values, deriving a column, and stripping fields that exist only in the UI.

namespace App\Filament\Resources\Orders\Pages;

use App\Filament\Resources\Orders\OrderResource;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Str;

class CreateOrder extends CreateRecord
{
    protected static string $resource = OrderResource::class;

    protected bool $shouldSendConfirmation = false;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $data['created_by_id'] = auth()->id();
        $data['reference'] = Str::upper(Str::random(8));

        // `send_confirmation` is a Toggle with no column behind it.
        // Stash it on the page so afterCreate() can still read it.
        $this->shouldSendConfirmation = (bool) ($data['send_confirmation'] ?? false);

        unset($data['send_confirmation']);

        return $data;
    }
}

Stashing the flag on a property is the part people miss. The mutate hook is the only place that sees the raw form state, and afterCreate() receives no arguments — so anything the form knows and the model doesn't has to be carried across on the page instance.

Never trust the array to be complete. Fields behind a visible() condition, or inside a collapsed section the user never opened, may simply be absent, so reach for $data['x'] ?? null rather than assuming the key exists. The same applies when a repeater or builder is storing nested form data — you're mutating an array of arrays, and a blind $data['items'][0] will bite.

On the edit page the equivalent is mutateFormDataBeforeSave(), with the same signature.

Take over persistence with handleRecordCreation#

When the record isn't a plain Model::create() — a domain service, a write across two models, a different connection — override handleRecordCreation(). It gets the mutated array and must return the saved model.

use App\Services\OrderCreator;
use Illuminate\Database\Eloquent\Model;

protected function handleRecordCreation(array $data): Model
{
    return app(OrderCreator::class)->create($data, auth()->user());
}

Check what you're replacing before you do. Filament's default implementation is not the one-liner the docs print — it builds the model, and if the resource is nested under a parent it associates the record with that parent instead of saving it directly. Override this method on a nested resource and you silently lose the parent association, leaving orphaned rows that only show up weeks later.

The edit counterpart is handleRecordUpdate(Model $record, array $data): Model, which defaults to $record->update($data).

One sequencing detail: Filament calls saveRelationships() on the form straight after this method returns and before afterCreate(). So relationship fields are persisted by the time your side effects run, but not while handleRecordCreation() is still executing.

Put side effects in afterCreate#

afterCreate() runs once the record exists and relationships are saved, with the model on $this->record. Notifications, queued jobs, audit entries and cache busting all belong here rather than inside the persistence method.

use App\Jobs\SendOrderConfirmation;

protected function afterCreate(): void
{
    if (! $this->shouldSendConfirmation) {
        return;
    }

    SendOrderConfirmation::dispatch($this->record)->afterCommit();
}

The afterCommit() call matters the moment you turn transactions on in the next step. Without it a queue worker can pick the job up and query for a row that the web request has not committed yet — the classic "model not found" in a job that works perfectly in tinker. The mechanics of that race are worth understanding properly if you dispatch much from panel code; I've covered dispatching jobs after database transactions commit separately.

beforeCreate() is the mirror image: it runs after the data is shaped but before anything is written, and $this->record is still null there. Any guard that needs the saved model has to wait for afterCreate().

Turn on database transactions before you depend on them#

Here is the correction to the thing everyone assumes: Filament v5 does not wrap saves in a database transaction by default. The CreateRecord::create() method calls beginDatabaseTransaction(), but that helper returns early unless transactions are enabled, and the panel default is false.

Enable it for the whole panel:

use Filament\Panel;

public function panel(Panel $panel): Panel
{
    return $panel
        // ...
        ->databaseTransactions();
}

Or for one page, when a panel-wide change is too blunt:

class CreateOrder extends CreateRecord
{
    protected ?bool $hasDatabaseTransactions = true;
}

With it on, the whole sequence from validation through afterCreate() runs inside one transaction, and any Throwable rolls the record back. That is usually what you want for a multi-model write — and occasionally a surprise, because a failing notification in afterCreate() now destroys a perfectly good record. If a side effect must not be able to undo the save, move it out of the hook and onto a model event that fires after commit, or guard it with its own try/catch.

Abort a save cleanly with halt()#

To stop a save without a half-written record, call $this->halt() from any before-hook or mutate method. It throws Filament\Support\Exceptions\Halt, which the page catches: the save stops, the form keeps its state, and the user stays where they are.

use Filament\Notifications\Notification;

protected function beforeCreate(): void
{
    if (auth()->user()->team->ordersToday() < 50) {
        return;
    }

    Notification::make()
        ->danger()
        ->title('Daily order limit reached')
        ->body('Your team can create 50 orders a day. Try again tomorrow.')
        ->persistent()
        ->send();

    $this->halt();
}

Send the notification before halting — the exception unwinds immediately, so anything after $this->halt() never runs.

Now the trap. When Filament catches Halt it asks the exception whether to roll back, and the default answer is no, so an open transaction is committed. Halt from afterCreate() with transactions enabled and you keep the record you were trying to reject. Pass the flag when that's wrong:

$this->halt(shouldRollbackDatabaseTransaction: true);

For permission checks rather than business guards, a policy is the better tool — it hides the action instead of letting the user fill a form and then rejecting it. Filament v5 authorization with policies, roles and permissions covers that side.

Choose between a hook, an observer and the model#

The decision rule is one question: which write paths must this logic cover? A page hook only fires when a human uses that panel page. An observer fires for every save() in the application.

namespace App\Observers;

use App\Models\Order;

class OrderObserver
{
    public function creating(Order $order): void
    {
        $order->reference ??= strtoupper(Str::random(8));
    }
}

Generating a reference belongs in the observer — an imported order needs one just as much as a hand-keyed one. Stamping created_by_id from auth()->id() belongs in the hook, because a queued job has no authenticated user and the observer would quietly write null.

Two things to watch. Observers do not fire for mass updates such as Order::query()->update([...]), which Eloquent events and mass updates goes into in detail — so a rule you move into an observer may be skipped by the bulk action you also expose on the table. And if you have both, the observer runs inside handleRecordCreation(), nested within the hook sequence, not before or after it.

My rule: invariants in the model or an observer, panel-specific behaviour in hooks, and nothing at all in an overridden save().

Test the hooks with Pest#

Filament pages are Livewire components, so hooks are testable without a browser. Point livewire() at the page class, fill the form, call the action, then assert on what landed in the database.

use App\Filament\Resources\Orders\Pages\CreateOrder;
use App\Models\Order;
use App\Models\User;

use function Pest\Livewire\livewire;

it('stamps the authenticated user and drops the UI-only toggle', function () {
    $user = User::factory()->create();

    $this->actingAs($user);

    livewire(CreateOrder::class)
        ->fillForm([
            'customer_name' => 'Ada Lovelace',
            'total' => 1200,
            'send_confirmation' => true,
        ])
        ->call('create')
        ->assertHasNoFormErrors();

    expect(Order::sole())
        ->created_by_id->toBe($user->id)
        ->reference->not->toBeEmpty();
});

A halt is asserted by its absence — no record, and no form errors either, because halt() is not a validation failure:

it('halts when the team is over its daily limit', function () {
    $user = User::factory()->overDailyOrderLimit()->create();

    $this->actingAs($user);

    livewire(CreateOrder::class)
        ->fillForm(['customer_name' => 'Ada Lovelace', 'total' => 1200])
        ->call('create')
        ->assertHasNoFormErrors();

    expect(Order::where('created_by_id', $user->id)->count())->toBe(50);
});

That assertHasNoFormErrors() is the assertion people leave out, and it's the one that proves the save was halted rather than rejected by validation. More patterns in testing Filament v5 resources with Pest.

Sidestep the gotchas that break on upgrade#

The hook names are stable; the behaviour around them has moved between majors. These are the ones that cost real time.

Modal create actions use different hooks entirely. If the resource creates records through a CreateAction in a modal rather than a dedicated Create page, none of the page hooks run. The modal equivalents are ->mutateDataUsing(), ->before() and ->after() chained onto the action. Note the rename: Filament 3.x called it mutateFormDataUsing(), v4 and v5 call it mutateDataUsing(), so a copied v3 snippet fails silently rather than erroring.

Trait hooks fire automatically in v5. Filament v5 added a convention where a trait can define afterCreateHandlesDrafts() and it's called in addition to the page's own afterCreate(). The page hook runs first, then each trait hook. Do not also call the trait method from the page hook or the side effect fires twice.

mutateFormDataBeforeFill() is a security boundary. Every non-$hidden model attribute is serialised into the Livewire payload sent to the browser. That's not a mass-assignment problem — only form fields are writable — but an API key or an internal flag on the model is now readable in devtools. unset() it in mutateFormDataBeforeFill().

$this->record is null in beforeCreate(). It's assigned from the return value of handleRecordCreation(). Anything needing the model waits for afterCreate().

A mutate hook that forgets to return gets you a silent empty insert. mutateFormDataBeforeCreate() returns array, so a missing return $data; is a TypeError in strict mode — but an early return $data; inside a conditional branch that skips your changes looks like the hook simply isn't running.

Wrapping Up#

Pick the hook by what it owns: shape data in mutateFormDataBeforeCreate(), guard in beforeCreate(), persist in handleRecordCreation(), and fire side effects in afterCreate(). Then decide, separately, whether the panel is the only write path — if it isn't, the logic is an observer, not a hook. Turn on ->databaseTransactions() deliberately rather than assuming it's already on, and remember that halt() commits unless you tell it not to.

Next, pin the behaviour down with Pest tests against your resource pages, and if you're still on v4, the Filament v5 upgrade guide covers what else moved.

FAQ#

How do I add the current user to a Filament form before saving?

Override mutateFormDataBeforeCreate() on the Create page class, set $data['user_id'] = auth()->id(), and return the array. It runs after validation and before the record is written, so the value is persisted without ever appearing as a form field. On the Edit page the equivalent method is mutateFormDataBeforeSave(). Do not use an observer for this — a queued job or console command has no authenticated user and would write null.

What is the difference between mutateFormDataBeforeCreate and beforeCreate?

mutateFormDataBeforeCreate() receives the validated form data as an array and returns the version you want saved — it is the only hook that can change the payload. beforeCreate() receives nothing and returns nothing; it is a guard where you run checks and optionally call $this->halt(). On the Create page the mutate hook runs first, then beforeCreate(). On the Edit page that order is reversed, with beforeSave() running before mutateFormDataBeforeSave().

How do I override how Filament saves a record?

Override handleRecordCreation(array $data): Model on the Create page, or handleRecordUpdate(Model $record, array $data): Model on the Edit page, and return the persisted model. Use it when the write is not a plain Model::create() — a domain service, a multi-model write, or a different connection. Avoid overriding save() itself: you lose Filament's validation, transaction and notification handling, and the internals change between releases.

How do I cancel a save in Filament?

Call $this->halt() from inside any before-hook or mutate method. It throws Filament\Support\Exceptions\Halt, which the page catches cleanly: the save stops, the form keeps its state and no partial record is written. Send any notification before the call, because nothing after it executes. If database transactions are enabled, pass shouldRollbackDatabaseTransaction: true — the default behaviour commits the open transaction rather than rolling it back.

Should I use a Filament hook or a model observer?

Ask which write paths the logic must cover. A page hook only fires when someone uses that panel page, so it suits panel-specific behaviour such as stamping the logged-in user or firing an admin-only notification. An observer fires on every save in the application, which is right for invariants like generating a slug or a reference that an importer needs too. Observers do not fire for mass updates, so a bulk action using a query-builder update will skip them.

Steven Richardson
Steven Richardson

CTO at Digitonic. Writing about Laravel, architecture, and the craft of leading software teams from the west coast of Scotland.