# Workflow automation in Filament, with triggers, approvals and queued runs

> Build an approval workflow in a Filament panel with Filament Flow. A record trigger, a condition, a sign-off in the panel, queued runs and a Pest test.

Most admin panels collect the same kind of rule sooner or later: when an order above a certain amount comes in, tell sales, ask a manager, and only then let it through. Then the amount moves, or a second manager joins, and the request to change the rule comes from someone who works in the panel, not in the codebase.

This guide builds that rule as a workflow in a Filament panel with [Filament Flow](https://packstub.dev/plugins/filament-flow), a free MIT plugin for Filament 4 and 5, so the people who own the rule can change it themselves. By the end you have an order sign-off that starts when a record is created, branches on the total, waits for a manager's decision in the panel and updates the order, plus a Pest test for it. The last sections cover when a few queued jobs or a state machine package are the better choice.

## A workflow is a trigger, a few steps, a decision and sometimes a person

Four kinds of things happen in a workflow, and Flow draws each as a node on a canvas:

- A **trigger** starts a run: a record was created, a date on a record arrived, a schedule is due, a webhook came in.
- An **action** does something: sends a notification or an email, updates a record, calls an HTTP endpoint.
- A **condition** branches on a true or false check, such as an attribute of the record.
- An **approval** pauses the run until a person decides, then continues along Approved, Rejected or Timed out.

The workflow in this guide uses one of each:

```mermaid
flowchart LR
    created(["Order created"])
    large{"Total over 1000?"}
    notify("Send notification\nto sales")
    ask{{"Ask for approval\nmanager, 2 days"}}
    approve("Update record\nstatus = approved")
    reject("Update record\nstatus = rejected")
    created --> large
    large -- "True" --> notify
    notify --> ask
    ask -- "Approved" --> approve
    ask -- "Rejected or timed out" --> reject
    large -- "False" --> approve
    classDef trigger fill:#17191e,stroke:#17191e,color:#fcfcfb
    classDef step fill:#fcfcfb,stroke:#dddeda,color:#17191e
    classDef gate fill:#fdf4e3,stroke:#c98a1b,color:#5c3d00,stroke-width:2px
    classDef done fill:#e3fcf1,stroke:#008c5e,color:#00613e
    classDef stop fill:#fcfcfb,stroke:#b7b9b4,color:#5d6167,stroke-dasharray:5 4
    class created trigger
    class large,notify step
    class ask gate
    class approve done
    class reject stop
```

Every run is stored with a step-by-step log, so "why was this order held?" has an answer in the panel.

## Install Flow and let a model start workflows

Flow needs PHP 8.3 or newer, Laravel 12 or 13 and Filament 4 or 5.

```bash
composer require packstub/filament-flow
php artisan packstub-flow:install
```

The install command publishes the config file and the migration, and offers to run the migration. Then add the `HasWorkflows` trait to each model that should start workflows. It fires the Record created, Record updated and Record deleted triggers from the model's own Eloquent events:

```php
use Illuminate\Database\Eloquent\Model;
use Packstub\Flow\Concerns\HasWorkflows;

class Order extends Model
{
    use HasWorkflows;

    protected $fillable = ['reference', 'total', 'status'];
}
```

Register the plugin on the panel:

```php
use Packstub\Flow\FlowPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        // ...
        ->databaseNotifications()
        ->plugin(
            FlowPlugin::make()
                ->navigationGroup('Automation'),
        );
}
```

The Send notification action and the approval request both show under the bell in the topbar. That needs `->databaseNotifications()` on the panel and Laravel's `notifications` table (`php artisan make:notifications-table`).

## Build the sign-off on the canvas

Open **Workflows** in the panel, press **New workflow**, name it "Sign off large orders", keep **Blank canvas** picked and press **Create workflow**. The workflow opens in the editor, inactive. Then:

1. **Add a trigger** and pick **Record created**. In its settings, set **Record type** to `Order`.
2. Press the plus next to the trigger's output and pick the **Record attribute** condition: attribute `total`, operator *is greater than*, value `1000`.
3. From the condition's **True** output, add **Send notification**: title `Order {{ model.reference }} is waiting for sign-off`, recipients `sales@example.com`. The `{{ model.reference }}` placeholder is filled in from the order that started the run. Recipients are email addresses of panel users, and placeholders work there too, for example `{{ model.owner.email }}`.
4. After it, add **Ask for approval**: approvers `manager@example.com`, request title `Approve order {{ model.reference }}`, timeout `2` days.
5. From **Approved**, add **Update record** with `status` set to `approved`. Drag the condition's **False** output to the same node, so small orders are approved without anyone being asked.
6. Add a second **Update record** with `status` set to `rejected`, and connect both **Rejected** and **Timed out** to it.
7. Press **Save changes**, then flip the **Active** switch.

Switching a workflow on checks it first. A node nothing leads to, or a required setting left empty, gets a red badge on the canvas and the switch stays off until it is fixed.

**Update record** writes through the model's `$fillable` rules, which is why `status` is fillable above. It also saves without firing events by default, so a workflow that listens for updates does not start itself again.

If you would rather not start from a blank canvas, the create page has a **Template** option with an "Approval before a record goes live" workflow, and [templates](https://packstub.dev/docs/filament-flow/templates) are plain JSON you can export from one panel and import in another.

## Triggers cover records, dates, schedules, webhooks and your own events

Record created is one of several ways in. The ones you will reach for most:

| Trigger | Starts a run when |
| --- | --- |
| Record created, updated, deleted | A model with `HasWorkflows` fires the Eloquent event. Record updated can watch attributes, with **Changed from** and **Changed to** |
| Date on a record | A date column, shifted by an offset, is reached: three days before `due_at`, one hour after `starts_at` |
| Schedule | A cron expression is due, such as `0 9 * * 1-5` for weekdays at 09:00, in a timezone you pick |
| Webhook | A `POST` hits the workflow's URL, with an optional HMAC-SHA256 signature check |
| Event | A Laravel event class of your choice is dispatched |
| Manual | Someone presses **Run now**, or a **Run workflow** action you add to a resource table |

Schedules and dates are evaluated every minute by `packstub-flow:cron`, which the plugin adds to Laravel's scheduler for you. A running scheduler is the only requirement.

Any trigger can also be dispatched from code with `Flow::dispatch()`, and `Flow::suppress()` switches triggers off around an import:

```php
use Packstub\Flow\Facades\Flow;
use Packstub\Flow\Nodes\Triggers\RecordCreated;

Flow::dispatch(RecordCreated::class, ['model' => $order]);

Flow::suppress(fn () => Order::factory()->count(1000)->create());
```

The [triggers page](https://packstub.dev/docs/filament-flow/triggers) lists every setting and the payload each trigger provides.

## Runs are inline by default and move to the queue with one setting

By default, a triggered workflow runs inside the request or model event that fired it. That is the simplest setup and a good fit for workflows that notify or update a record. Once a workflow sends email or calls another service, put runs on the queue:

```dotenv
PACKSTUB_FLOW_QUEUE=true
PACKSTUB_FLOW_QUEUE_CONNECTION=redis
PACKSTUB_FLOW_QUEUE_NAME=flows
```

Each matching workflow then becomes a `RunWorkflowJob`, dispatched after the surrounding database transaction commits, so a run never sees a record that was rolled back.

Retries are set per step instead of per job. The run job has `tries = 1`, because retrying a whole run would repeat the steps that already succeeded. Each action node has an **Error handling** section with the number of retries (0 to 10), the seconds between them, and what happens after the last failure: fail the run, log it and continue, or follow a red **Error** output to steps of your own.

A failed run can be started again from the Runs tab with **Run again** once the cause is fixed.

A **Wait** step, an approval and a **Wait for signal** step (covered in the next section) all pause the run and continue it later through the queue. Keep a worker running (`php artisan queue:work`) when a workflow uses them. An approval is stored as a database row, so it survives deploys and queue restarts. The details are on the [queue and scheduling page](https://packstub.dev/docs/filament-flow/queue-and-scheduling).

## An approval is decided from the notification, the Approvals page or your code

When the run reaches **Ask for approval**, it goes into the Waiting status and the approvers are told. There are three places to decide:

- **The notification** under the bell, with **Approve** and **Reject** buttons. An email with signed Approve and Reject links can be sent as well.
- **The Approvals page**, next to Workflows in the navigation, with a badge counting the requests waiting for the signed-in user. Each request shows its title, the workflow and the record it is about, and takes an optional comment.
- **Your own code**, with `Flow::resolveWait($wait, 'approved', ['comment' => '...'], 'manager@example.com')`, where `$wait` is the stored row for the request. The first decision wins.

The notification buttons and the email links are signed URLs. They need a signed-in user who is one of the approvers, and they are valid for 72 hours by default.

After the decision, the steps on that branch can read `{{ approval.outcome }}`, `{{ approval.by }}`, `{{ approval.comment }}` and `{{ approval.at }}`, which is enough to write "Approved by {{ approval.by }}" into a note or a message.

Sometimes the thing to wait for is a system, such as a payment provider. **Wait for signal** pauses the same way, and continues when your code calls `Flow::signal("payment.{$order->id}")`. Approvals and signals are both covered on the [approvals and signals page](https://packstub.dev/docs/filament-flow/approvals).

## Test the workflow like any other feature

A workflow is stored as JSON with two lists, `nodes` and `edges`, and the runner reads the same structure the canvas saves. So a test can create the definition, trigger it and assert on the run. The `flowNode()` and `flowEdge()` helpers below are the two small functions from the [testing page](https://packstub.dev/docs/filament-flow/testing); they build one node and one edge.

```php
use App\Models\Order;
use App\Models\User;
use Packstub\Flow\Enums\RunStatus;
use Packstub\Flow\Facades\Flow;
use Packstub\Flow\Models\Workflow;
use Packstub\Flow\Models\WorkflowRun;
use Packstub\Flow\Models\WorkflowWait;
use Packstub\Flow\Nodes\Actions\RequestApproval;
use Packstub\Flow\Nodes\Actions\SendNotification;
use Packstub\Flow\Nodes\Actions\UpdateRecord;
use Packstub\Flow\Nodes\Conditions\RecordAttribute;
use Packstub\Flow\Nodes\Triggers\RecordCreated;

// flowNode() and flowEdge() come from the testing page: copy them into tests/Pest.php.
function signOffWorkflow(): Workflow
{
    return Workflow::create([
        'name' => 'Sign off large orders',
        'is_active' => true,
        'definition' => [
            'nodes' => [
                flowNode('created', 'trigger', RecordCreated::class, ['model_class' => Order::class]),
                flowNode('large', 'condition', RecordAttribute::class, ['attribute' => 'total', 'operator' => '>', 'value' => '1000']),
                flowNode('notify', 'action', SendNotification::class, [
                    'title' => 'Order {{ model.reference }} is waiting for sign-off',
                    'recipients' => 'sales@example.com',
                ]),
                flowNode('ask', 'action', RequestApproval::class, [
                    'approvers' => 'manager@example.com',
                    'title' => 'Approve order {{ model.reference }}',
                    'timeout' => 2,
                    'timeout_unit' => 'days',
                ]),
                flowNode('approve', 'action', UpdateRecord::class, ['attributes' => ['status' => 'approved']]),
                flowNode('reject', 'action', UpdateRecord::class, ['attributes' => ['status' => 'rejected']]),
            ],
            'edges' => [
                flowEdge('created', 'large'),
                flowEdge('large', 'notify', 'true'),
                flowEdge('notify', 'ask'),
                flowEdge('ask', 'approve', 'approved'),
                flowEdge('ask', 'reject', 'rejected'),
                flowEdge('ask', 'reject', 'timed_out'),
                flowEdge('large', 'approve', 'false'),
            ],
        ],
    ]);
}

it('holds a large order until the manager approves it', function (): void {
    $sales = User::factory()->create(['email' => 'sales@example.com']);
    $manager = User::factory()->create(['email' => 'manager@example.com']);
    signOffWorkflow();

    $order = Order::factory()->create(['total' => 2500, 'status' => 'pending']);

    $run = WorkflowRun::query()->sole();
    $wait = WorkflowWait::query()->sole();

    expect($run->status)->toBe(RunStatus::Delayed)
        ->and($order->fresh()->status)->toBe('pending')
        ->and($sales->notifications()->count())->toBe(1)
        ->and($manager->notifications()->count())->toBe(1)
        ->and($wait->meta['title'])->toBe("Approve order {$order->reference}");

    Flow::resolveWait($wait, 'approved', ['comment' => 'Known customer'], 'manager@example.com');

    expect($run->fresh()->status)->toBe(RunStatus::Success)
        ->and($order->fresh()->status)->toBe('approved');
});

it('approves a small order without asking', function (): void {
    signOffWorkflow();

    $order = Order::factory()->create(['total' => 100, 'status' => 'pending']);

    expect(WorkflowWait::query()->count())->toBe(0)
        ->and($order->fresh()->status)->toBe('approved')
        ->and(collect(WorkflowRun::query()->sole()->steps)->pluck('node_id')->all())
        ->toBe(['created', 'large', 'approve']);
});
```

`RunStatus::Delayed` is the stored name of the Waiting status. With the `sync` queue driver, the usual test setup, the run continues as soon as `resolveWait()` is called. The timeout branch is tested by moving the clock and running the cron command:

```php
$this->travel(3)->days();
$this->artisan('packstub-flow:cron')->assertSuccessful();

expect($order->fresh()->status)->toBe('rejected');
```

In the panel, the **Test** button on a workflow does a dry run with a record you pick. Conditions are evaluated for real, and every action that would send or write something is logged as simulated instead, so you can try a change against a real order before switching it on.

## When a few queued jobs or a state machine are the right size

A workflow engine earns its place when the rules change often and people outside the codebase should see and edit them. Other tools are the better pick in other situations.

- **Laravel's queued jobs** are the right size when the process is fixed, lives in code and is owned by developers. A [job chain](https://laravel.com/docs/queues#job-chaining) with `Bus::chain()` runs steps in order, each job has its own `tries` and `backoff`, and the whole thing is reviewed and deployed like any other code. For three steps that rarely change, that is less to run and less to learn.
- **A state machine package** is the right tool when the question is "which states can this record be in, and which moves are allowed". [spatie/laravel-model-states](https://github.com/spatie/laravel-model-states) gives each state its own class and keeps the allowed transitions next to the model, where they are enforced no matter who changes the record.
- **A dedicated approvals package** fits when approval is the whole feature. [ringlesoft/laravel-process-approval](https://github.com/ringlesoft/laravel-process-approval) adds multi-level approvals to Eloquent models, with steps tied to the roles you already have and a Blade component for the approval actions.

These combine well. When spatie/laravel-model-states is installed, Flow offers a **State transitioned** trigger and a **Transition state** action, so the state machine keeps deciding what is allowed and the workflow handles what happens around a transition: who is told, who signs off, what is updated afterwards.

A step that needs real code is a small class: an action with a `handle()` method, registered on the plugin, as the [extending page](https://packstub.dev/docs/filament-flow/extending) shows.

## Where Flow fits, and Form Builder next to it

Flow is one way to build a workflow like this one, and it suits the case this guide started with: rules that live in the panel, drawn on a canvas by the people who own them, with a log of every run, a history of every version and approvals decided in the same panel. Developers keep the parts that belong in code, the models, the custom steps and the tests.

Many approval processes begin with a request someone fills in: a leave request, a purchase request, a refund form. [Filament Form Builder](https://packstub.dev/plugins/filament-form-builder), also free and MIT, is the other half of that.

Forms are designed in the panel and rendered with Blade, Livewire or a JSON API, and every submission can be posted as JSON to a webhook URL. Point that URL at a workflow's **Webhook** trigger and each submission starts a run, with the answers available as `{{ webhook.data.data.email }}` and so on. The [Form Builder docs](https://packstub.dev/docs/filament-form-builder) cover the forms side.

If you would like this set up in your app for you, XLITE, the company behind Packstub, offers [forms and an approval workflow as a fixed-price package](https://xlite.dev/services/forms-and-approvals/).

To try Flow yourself, the [installation page](https://packstub.dev/docs/filament-flow/installation) ends with a five-step first workflow, and the sign-off above is a good second one.
