Skip to content

Event-Driven Triggers

Laravel events can automatically trigger workflows by implementing the TriggersWorkflow interface. No configuration needed -- the wildcard listener is registered automatically by the service provider.

How It Works

  1. Your Laravel event implements TriggersWorkflow
  2. When the event is dispatched via event(), the wildcard listener intercepts it
  3. The listener calls toWorkflowEvent() to convert it to a WorkflowEvent DTO
  4. All workflows bound to that event name are dispatched asynchronously

Implementing TriggersWorkflow

php
namespace App\Events;

use Workflowable\Workflowable\Contracts\TriggersWorkflow;
use Workflowable\Workflowable\Abstracts\WorkflowEvent;
use App\WorkflowEvents\OrderSubmitted;

class OrderPlaced implements TriggersWorkflow
{
    public function __construct(
        public readonly int $orderId,
        public readonly float $amount,
    ) {}

    public function toWorkflowEvent(): WorkflowEvent
    {
        return new OrderSubmitted(
            orderId: $this->orderId,
            amount: $this->amount,
        );
    }

    // Optional: provide a user ID for the workflow instance
    public function getUserId(): int
    {
        return auth()->id();
    }
}

Dispatching

Just dispatch your Laravel event normally:

php
event(new \App\Events\OrderPlaced(orderId: 123, amount: 1500.00));

This automatically triggers all workflows bound to the event name returned by the WorkflowEvent DTO. Workflows are always dispatched asynchronously via Workflowable::dispatch().

Error Handling

  • If no workflows match the event, it's silently logged at debug level -- no exceptions thrown
  • If a workflow fails to trigger, the error is logged but does not propagate to the original event dispatch

Optional getUserId()

If your event class implements a getUserId() method, the returned user ID is passed to Workflowable::dispatch() and recorded on the workflow instance as created_by.

When to Use Event-Driven Triggers

Use TriggersWorkflow when you want existing domain events to transparently trigger workflows without modifying the dispatch site. This is ideal for:

  • Decoupling workflow triggering from business logic
  • Adding workflow behavior to existing events without changing dispatch code
  • Fire-and-forget scenarios where you don't need the instance collection back

For explicit control or when you need the returned instances, use Direct Dispatch instead.