Skip to content

Installation & Setup

Jean-Marc Strauven edited this page Aug 6, 2025 · 2 revisions

πŸ“¦ Installation & Setup

This guide will walk you through installing and configuring Laravel Statecraft in your Laravel application.

πŸ”§ Requirements

Laravel Statecraft requires:

  • PHP: 8.1 or higher
  • Laravel: 10.x or 11.x
  • Composer: For package management

πŸ“₯ Installation

1. Install via Composer

Install Laravel Statecraft using Composer:

composer require grazulex/laravel-statecraft

πŸ’‘ Auto-Discovery
The service provider will be automatically registered thanks to Laravel's package auto-discovery feature.

2. Publish Configuration

Publish the configuration file to customize Laravel Statecraft:

php artisan vendor:publish --tag=statecraft-config

This creates config/statecraft.php with the default configuration.

3. Publish Migrations (Optional)

If you want to track state history, publish and run the migrations:

php artisan vendor:publish --tag=statecraft-migrations
php artisan migrate

This creates the state_machine_histories table for tracking state changes.

βš™οΈ Configuration

The configuration file config/statecraft.php contains several important settings:

State Machine Directory

'state_machines_path' => resource_path('state-machines'),

Defines where your YAML state machine definitions are stored.

History Tracking

'enable_history' => true,

Enable or disable state change history tracking.

Cache Settings

'cache' => [
    'enabled' => true,
    'ttl' => 3600, // 1 hour
    'prefix' => 'statecraft',
],

Configure caching for improved performance.

Event Broadcasting

'events' => [
    'enabled' => true,
    'broadcast' => false,
],

Control event firing and broadcasting.

πŸ“ Directory Structure

After installation, create the following directory structure:

resources/
β”œβ”€β”€ state-machines/           # YAML state machine definitions
β”‚   β”œβ”€β”€ OrderStateMachine.yaml
β”‚   β”œβ”€β”€ UserStateMachine.yaml
β”‚   └── ...
└── ...

app/
β”œβ”€β”€ StateMachine/
β”‚   β”œβ”€β”€ Guards/              # Guard classes
β”‚   β”‚   β”œβ”€β”€ PaymentGuard.php
β”‚   β”‚   └── ...
β”‚   └── Actions/             # Action classes
β”‚       β”œβ”€β”€ ProcessPayment.php
β”‚       └── ...

πŸ—οΈ Create Your First State Machine

1. Generate State Machine Files

Use the Artisan command to generate your state machine:

php artisan statecraft:make OrderStateMachine --model=Order

This creates:

  • resources/state-machines/OrderStateMachine.yaml - State machine definition
  • Example guard and action classes

2. Configure Your Model

Add the HasStateMachine trait to your Eloquent model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Grazulex\LaravelStatecraft\Traits\HasStateMachine;

class Order extends Model
{
    use HasStateMachine;

    protected $stateMachine = 'OrderStateMachine';

    protected $fillable = [
        'amount',
        'customer_email',
        'status', // This will store the current state
    ];
}

3. Add State Column to Migration

Ensure your model's table has a column to store the current state:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->string('status')->default('pending')->after('amount');
        });
    }

    public function down()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn('status');
        });
    }
};

βœ… Verify Installation

Test that everything is working correctly:

<?php

use App\Models\Order;

// Create an order
$order = Order::create([
    'amount' => 100.00,
    'customer_email' => '[email protected]'
]);

// Check initial state
echo $order->getCurrentState(); // Should output: pending

// Verify state machine is loaded
$stateMachine = $order->getStateMachine();
echo $stateMachine->getName(); // Should output: OrderStateMachine

πŸ” Troubleshooting

Common Issues

State machine file not found

  • Ensure your YAML file exists in resources/state-machines/
  • Check the filename matches your $stateMachine property

Model not found error

  • Verify the model class exists and the namespace is correct in your YAML

Permission errors

  • Ensure Laravel can write to the storage and cache directories

Cache issues

  • Clear the application cache: php artisan cache:clear
  • Disable cache temporarily in config for debugging

Debug Mode

Enable debug mode for additional logging:

// In config/statecraft.php
'debug' => env('STATECRAFT_DEBUG', false),

Set in your .env file:

STATECRAFT_DEBUG=true

πŸš€ What's Next?

Now that Laravel Statecraft is installed and configured:

  1. Learn the Basics - Understand core concepts
  2. YAML Configuration - Master the YAML syntax
  3. Explore Examples - See real-world implementations

Having issues? Check our troubleshooting guide or create an issue on GitHub.

Clone this wiki locally