-
-
Notifications
You must be signed in to change notification settings - Fork 0
Examples Collection
This page provides a comprehensive collection of real-world examples demonstrating Laravel Statecraft's capabilities. Each example includes complete YAML configurations, model setup, guards, actions, and tests.
Complete e-commerce order processing workflow
A comprehensive example covering the entire order lifecycle from creation to delivery, including:
- Payment processing with multiple payment methods
- Inventory management and reservation
- Shipping integration with tracking
- Customer notifications and refund handling
- Complex guard logic and conditional transitions
Use Cases: E-commerce platforms, order management systems, fulfillment workflows
Content management and publishing workflow
A sophisticated content management workflow featuring:
- Multi-step editorial review process
- Role-based permissions and approvals
- Content scheduling and publication
- Revision tracking and rollback capabilities
- SEO and metadata management
Use Cases: CMS platforms, blog management, editorial workflows, content publishing
Subscription lifecycle management
A complete subscription management system including:
- Trial period management
- Payment processing and billing cycles
- Subscription upgrades and downgrades
- Payment failure handling and dunning
- Cancellation and reactivation flows
Use Cases: SaaS platforms, membership sites, subscription services
π― Event Usage Example
Advanced event handling and integration
Demonstrates comprehensive event system usage:
- Real-time notifications and webhooks
- Analytics and metrics collection
- External system integrations
- Audit logging and compliance
- Custom event listeners and broadcasting
Use Cases: Real-time applications, integration platforms, audit systems
Perfect for learning the basics:
# Simple approval workflow
name: SimpleApproval
model: App\Models\Document
initial_state: draft
states:
- name: draft
description: Document is being edited
- name: pending
description: Awaiting approval
- name: approved
description: Document approved
- name: rejected
description: Document rejected
transitions:
- name: submit
from: draft
to: pending
- name: approve
from: pending
to: approved
guard: IsManager
- name: reject
from: pending
to: rejected
guard: IsManager
Handle multiple source states:
transitions:
- name: cancel
from: [draft, pending, approved]
to: cancelled
action: NotifyStakeholders
Combine multiple conditions:
transitions:
- name: auto_approve
from: pending
to: approved
guard:
and:
- HasMinimumAmount
- IsRegularCustomer
- not: RequiresManualReview
- Order Processing - Complete order fulfillment workflow
- Inventory Management - Stock reservation and allocation
- Customer Service - Support ticket resolution workflow
- Product Catalog - Product approval and publishing
- User Onboarding - Multi-step user registration and verification
- Subscription Management - Billing cycles and plan changes
- Feature Rollouts - Gradual feature deployment workflow
- Support Tickets - Customer support case management
- Editorial Workflow - Content creation, review, and publishing
- Media Processing - File upload, processing, and approval
- Comment Moderation - User-generated content approval
- SEO Optimization - Content optimization workflow
- Loan Applications - Multi-step approval process
- KYC Compliance - Customer verification workflow
- Transaction Processing - Payment validation and settlement
- Risk Assessment - Automated risk evaluation
Start with these simple workflows:
states: [draft, pending, approved, rejected]
transitions:
- {name: submit, from: draft, to: pending}
- {name: approve, from: pending, to: approved, guard: IsManager}
- {name: reject, from: pending, to: rejected, guard: IsManager}
states: [todo, in_progress, review, done]
transitions:
- {name: start, from: todo, to: in_progress}
- {name: finish, from: in_progress, to: review}
- {name: complete, from: review, to: done, guard: IsAssignee}
More complex business logic:
states: [draft, sent, paid, overdue, cancelled]
transitions:
- name: send
from: draft
to: sent
guard: HasValidItems
action: SendInvoiceEmail
- name: pay
from: [sent, overdue]
to: paid
guard: PaymentValidation
action: ProcessPayment
- name: mark_overdue
from: sent
to: overdue
action: SendReminderEmail
Complex workflows with multiple conditions:
states: [applied, screening, interview, background_check, offer, hired, rejected]
transitions:
- name: screen
from: applied
to: screening
guard:
and:
- HasRequiredSkills
- PassesInitialFilter
- name: schedule_interview
from: screening
to: interview
guard:
or:
- IsRecommended
- HasExceptionalProfile
action: ScheduleInterviewAction
- name: make_offer
from: background_check
to: offer
guard:
and:
- PassedBackgroundCheck
- InterviewScoreAboveThreshold
- BudgetAvailable
action: PrepareOfferAction
Sequential steps with no branching:
- User registration β verification β activation
- Order β payment β fulfillment β delivery
Multiple possible paths:
- Application β approved/rejected
- Content β published/archived/deleted
Multiple independent processes:
- Order processing + inventory update
- Content creation + SEO optimization
Repeating cycles:
- Subscription billing cycles
- Periodic review processes
- Retry mechanisms
- Document approval
- Budget approval
- Leave requests
- Purchase orders
- Article publishing
- Media processing
- Comment moderation
- Translation workflows
- Payment processing
- Order fulfillment
- Refund handling
- Billing cycles
- Registration flows
- Profile verification
- Permission escalation
- Account suspension
Each example includes comprehensive testing strategies:
public function test_order_can_be_paid()
{
$order = Order::factory()->pending()->create(['amount' => 100]);
$this->assertTrue($order->canTransitionTo('pay'));
$order->transitionTo('pay');
$this->assertEquals('paid', $order->getCurrentState());
}
public function test_complete_order_workflow()
{
$order = Order::factory()->create();
$order->transitionTo('pay');
$order->transitionTo('process');
$order->transitionTo('ship');
$order->transitionTo('deliver');
$this->assertEquals('delivered', $order->getCurrentState());
$this->assertCount(4, $order->getStateHistory());
}
public function test_order_notifications_sent()
{
Mail::fake();
$order = Order::factory()->create();
$order->transitionTo('pay');
Mail::assertSent(OrderConfirmationMail::class);
}
// Efficient bulk state transitions
Order::whereIn('id', $orderIds)
->chunk(100, function ($orders) {
foreach ($orders as $order) {
if ($order->canTransitionTo('auto_cancel')) {
$order->transitionTo('auto_cancel');
}
}
});
// Cache state machine definitions
$stateMachine = Cache::remember(
"state_machine.{$modelClass}",
3600,
fn() => StateMachine::load($modelClass)
);
// Before: Manual state management
$order->status = 'paid';
$order->paid_at = now();
$order->save();
// After: State machine
$order->transitionTo('pay');
// Before: Simple enum
enum OrderStatus: string {
case PENDING = 'pending';
case PAID = 'paid';
case SHIPPED = 'shipped';
}
// After: Full state machine with business logic
$order->transitionTo('pay', ['payment_method' => 'card']);
try {
$order->transitionTo('ship');
} catch (TransitionNotAllowedException $e) {
Log::warning("Cannot ship order {$order->id}: {$e->getMessage()}");
// Handle gracefully
}
guard:
and:
- HasValidPayment
- not: IsBlacklisted
- or:
- IsVIPCustomer
- HasManagerApproval
// Listen for specific state changes
Event::listen(StateTransitioned::class, function ($event) {
if ($event->model instanceof Order && $event->toState === 'shipped') {
// Send tracking information
dispatch(new SendTrackingInfoJob($event->model));
}
});
- Choose an Example - Pick one that matches your use case
- Copy the Configuration - Use the YAML as a starting point
- Customize Guards and Actions - Implement your business logic
- Add Tests - Ensure your workflow works correctly
- Iterate and Improve - Refine based on real usage
Each example follows this structure:
- Overview - What the example demonstrates
- YAML Configuration - Complete state machine definition
- Model Setup - Eloquent model configuration
- Guards - Business rule implementations
- Actions - Side effect implementations
- Events - Event handling examples
- Tests - Comprehensive test suite
- Usage - How to use in your application
- YAML Configuration Guide - Complete syntax reference
- Guards & Actions Guide - Implementation patterns
- Testing Guide - Testing strategies
- Events System - Event handling
Ready to explore? Start with the Order Workflow Example for a comprehensive introduction to Laravel Statecraft's capabilities.
π― Laravel Statecraft - Advanced State Machine Implementation for Laravel
Navigate: π Home | π¦ Installation | π Basic Guide | π YAML Config | π‘ Examples
Resources: π‘οΈ Guards & Actions | π― Events | π State History | π§ͺ Testing | π¨ Commands
π Community Resources:
Made with β€οΈ for the Laravel community β’ Contribute β’ License