Search by

ibrahim-sajib / laravel-approval-flow

ibrahim-sajib

Configurable multi-step approval workflows (sequential, parallel, optional approvers, conditions, delegation) for any Eloquent model.

Package info

github.com/ibrahim-sajib/laravel-approval-flow

pkg:composer/ibrahim-sajib/laravel-approval-flow

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0-beta 2026-11-22 16:54 UTC

This package is auto-updated.

Last update: 2026-11-22 17:10:05 UTC


README

Latest Version on Packagist

Configurable multi-step approval workflows for any Eloquent model.

Current release: 0.1.0-beta. The API is usable but may still change before 1.0.0.

  • Sequential steps, parallel steps (all / any), optional approvers
  • Steps generated per requester (personal approver chains)
  • Conditional steps (closures or JSON rules), workflow bypass
  • Submit, approve, reject, return to requester, resubmit, withdraw, cancel
  • Delegation (date range, optionally per workflow)
  • Observers, full append-only history, frontend-ready timeline
  • Self-approval policy (maker-checker), comment rules
  • Workflows in code or in the database (for admin UIs)
  • Business logic in model hooks (inside the transaction, roll back on failure)
  • Events dispatched after commit, with an atomic guard against double approval
  • int / uuid / ulid keys, configurable connection & table prefix (multi-tenancy friendly)

Requires PHP 8.2+ and Laravel 11, 12 or 13 (Laravel 13 needs PHP 8.3+).

Key-type limitation: one installation uses one database.morph_key_type (int, uuid or ulid) for approvable, requester, approver and actor models. Mixed integer and UUID keys in the same installation are not supported.

Installation

composer require ibrahim-sajib/laravel-approval-flow
php artisan vendor:publish --tag=approval-flow-config
php artisan vendor:publish --tag=approval-flow-migrations
php artisan migrate

Using UUID or ULID primary keys? Set database.morph_key_type in config/approval-flow.php before running the migration.

Quick start

1. Make a model approvable

use ApprovalFlow\Concerns\HasApprovals;
use ApprovalFlow\Contracts\Approvable;
use ApprovalFlow\Models\ApprovalRequest;

class PurchaseOrder extends Model implements Approvable
{
    use HasApprovals;

    public function approvalWorkflowKey(): string { return 'purchase-order'; }

    public function approvalRequester(): ?Model { return $this->user; }

    public function approvalContext(): array { return ['amount' => (string) $this->amount]; }

    public function onApprovalApproved(ApprovalRequest $request): void
    {
        $this->update(['status' => 'approved']);
    }
}

2. Define the workflow (e.g. in AppServiceProvider::boot())

use ApprovalFlow\Definitions\Step;
use ApprovalFlow\Facades\ApprovalFlow;

ApprovalFlow::define('purchase-order')
    ->step('Manager', fn (Step $s) => $s->approvers(fn ($po) => $po->user->manager)->slaHours(24))
    ->step('Finance', fn (Step $s) => $s->approvers(fn () => User::where('team', 'finance')->get())->any())
    ->step('CEO', fn (Step $s) => $s
        ->approvers(fn () => User::where('role', 'ceo')->first())
        ->when(fn ($po, $requester, array $context) => (float) $context['amount'] > 100000))
    ->selfApproval('forbid');

3. Use it

$po->approvalFlow()->submit();                      // requester = approvalRequester() or auth user
$po->approvalFlow()->approve($manager, 'OK');       // actor defaults to auth()->user()
$po->approvalFlow()->reject($finance, 'No budget'); // a comment is required by default
$po->approvalFlow()->returnToRequester($ceo, 'Add a quotation');
$po->approvalFlow()->resubmit();
$po->approvalFlow()->withdraw();
$po->approvalFlow()->cancel($admin, 'Duplicate', force: true);

$po->approvalFlow()->status();             // RequestStatus enum
$po->approvalFlow()->canBeActionedBy($user);
$po->approvalFlow()->currentApprovers();
$po->approvalFlow()->timeline($user);      // array for your UI
$po->approvalFlow()->history();

PurchaseOrder::wherePendingApprovalFor($user)->get();
PurchaseOrder::whereApprovalStatus('approved')->get();
ApprovalFlow::pendingTasksFor($user)->get(); // inbox across all workflows

Rules

Topic Behaviour
Steps Run in order. A step is decided by its required approvers only.
all / any all: everyone must approve, one rejection rejects. any: one approval is enough (others become skipped), rejected only when everyone rejects.
Optional approvers Become pending when their step is reached, may approve/reject for the record, never change the outcome, never block the next step, cannot return.
Conditions Evaluated once at submit; a failing step is left out.
Snapshot Approvers are resolved at submit (and at resubmit). Later config changes do not touch running requests.
Self approval skip (default): requester's task is created as skipped. forbid: requester is removed from all steps and can never act (also not as delegate). allow.
Reject reject_behavior reject (final) or return (back to the requester).
Return / resubmit Returned requests are resubmitted as a new round; old rounds stay in history.
Withdraw before_any_action (default), while_pending, never. Only the requester.
Cancel Open requests; approved ones only with force: true (hook gets the previous status).
Delegation Delegate may act for the delegator inside the date range; acted_by and history record who really acted.
Transactions Every action is one transaction; the request row is locked and the task update is an atomic conditional update, so the same task cannot be approved twice (also on SQLite). Hooks run inside it, events after commit.

Workflow settings

Defaults live in config/approval-flow.php (defaults), and each workflow can override them:

ApprovalFlow::define('leave-request')
    ->selfApproval('skip')                  // skip | forbid | allow
    ->rejectBehavior('reject')              // reject | return
    ->emptyStep('skip')                     // fail | skip
    ->emptyChain('fail')                    // fail | auto_approve
    ->optionalCanActAfterCompletion(true)
    ->withdraw('before_any_action')         // before_any_action | while_pending | never
    ->commentRequiredOn(['reject', 'return'])
    ->bypassWhen(fn ($leave) => config('features.leave_approval') === false)
    ->observers(fn ($leave) => $leave->employee->hrPartners);

Approvers

approvers() accepts a model, a list/collection of models, ResolvedApprover objects (ResolvedApprover::optional($model)), a closure returning any of those, or a class implementing ApprovalFlow\Contracts\ApproverResolver.

Personal chains (one step per person, each with its own optional flag):

ApprovalFlow::define('leave-request')->steps(fn ($leave) => $leave->employee->approvers
    ->sortBy('pivot.order')
    ->map(fn ($approver) => Step::make($approver->name)
        ->approvers($approver)
        ->optional((bool) $approver->pivot->is_optional))
    ->all());

If your approvers are not User models (e.g. Employee), bind an actor resolver:

class EmployeeActorResolver implements \ApprovalFlow\Contracts\ActorResolver
{
    public function resolve(): ?Model { return auth()->user()?->employee; }
}
// config/approval-flow.php: 'actor_resolver' => App\Approval\EmployeeActorResolver::class,

Database workflows

Rows of approval_workflows (key, name, is_active, definition JSON) override code definitions with the same key (see definitions.priority).

{
  "settings": {"self_approval": "forbid"},
  "steps": [
    {"name": "Manager", "approvers": {"type": "model", "model": "App\\Models\\User", "ids": [3]}, "sla_hours": 24},
    {"name": "Finance", "mode": "any", "approvers": {"type": "resolver", "resolver": "finance-team"}},
    {"name": "CEO", "approvers": {"type": "model", "model": "App\\Models\\User", "ids": [1]},
     "condition": {"field": "amount", "operator": ">", "value": 100000}}
  ]
}

"model" accepts a fully-qualified class name (as above) or a morph-map alias registered with Relation::enforceMorphMap(['user' => \App\Models\User::class]). Resolver aliases are mapped in config('approval-flow.resolvers'). Condition operators: =, !=, >, >=, <, <=, in, not_in, combined with {"all": [...]} / {"any": [...]}.

Delegation

ApprovalFlow::delegations()->delegate($manager, $deputy, now(), now()->addWeek(), workflowKey: null, reason: 'Leave');
ApprovalFlow::delegations()->revoke($delegation);

Events

All extend ApprovalFlow\Events\ApprovalEvent ($event->request, $event->workflowKey()) and are dispatched after commit: ApprovalSubmitted, ApprovalResubmitted, ApprovalStepActivated ($stepOrder, $tasks), ApprovalTaskActioned ($task, $action, $actor, $context with step snapshots before/after advancement), ApprovalApproved, ApprovalRejected, ApprovalReturned, ApprovalCancelled, ApprovalTaskOverdue ($task).

Schedule reminders: Schedule::command('approval-flow:remind')->hourly();

Exceptions

All extend ApprovalFlow\Exceptions\ApprovalFlowException and have errorCode(): approval.workflow_not_found, approval.already_submitted, approval.no_request, approval.request_not_pending, approval.not_an_approver, approval.not_your_turn, approval.already_actioned, approval.self_approval_not_allowed, approval.comment_required, approval.empty_chain, approval.empty_step, approval.actor_required, approval.action_not_allowed, approval.invalid_definition.

// bootstrap/app.php
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(fn (\ApprovalFlow\Exceptions\ApprovalFlowException $e) =>
        response()->json(['message' => $e->getMessage(), 'code' => $e->errorCode()], 422));
})

Multi-tenancy

Keep database.connection = null, publish the migration into your tenant migrations folder, run reminders per tenant (e.g. php artisan tenants:run approval-flow:remind).

Testing

composer test
APPROVAL_FLOW_TEST_DB=mysql DB_USERNAME=root DB_PASSWORD=secret composer test
APPROVAL_FLOW_TEST_DB=pgsql DB_USERNAME=postgres DB_PASSWORD=secret composer test

License

MIT