PHP code example of datomatic / laravel-enum-state-machine

1. Go to this page and download the library: Download datomatic/laravel-enum-state-machine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

datomatic / laravel-enum-state-machine example snippets


return [
/*
    |--------------------------------------------------------------------------
    | Soft Mode Configuration
    |--------------------------------------------------------------------------
    |
    | The 'soft_mode' configuration allows for handling errors without
    | interrupting the application's execution. When this option is enabled,
    | no exceptions are thrown during state transitions and logged instead.
    | This helps prevent unexpected crashes, ensuring
    | greater application resilience, especially in scenarios where a failure
    | in the state machine should not disrupt the main program flow.
    | You can configure this modality for each model casting
    |
    */
    'soft_mode' => env('LARAVEL_ENUM_STATE_MACHINE_SOFT_MODE', false),
];

    'model_hooks' => [
        ...,
        LaravelEnumStateMachineModelIdeHelperHook::class,
    ],

class TestModel extends Model
{
    //Laravel 10
    protected $casts = [
        'status' => AsEnumStateMachine::class.':'.StatusEnum::class,  // ',true' for soft mode
    ];
    
    //Laravel 11
    protected function casts(): array
    {
        return [
            'field_name' => AsEnumStateMachine::of(FieldEnum::class, false),
        ];
    }

    /** 
     * This method name is composed by the enum field name (camelCase) + Transitions 
     */
    public function statusTransitions(?StatusEnum $from, ?StatusEnum $to): bool
    {
        return match ($from) {
            null => true, // initial state permitted to all states
            StatusEnum::PUBLIC => match ($to) {
                StatusEnum::PRIVATE => true,
                StatusEnum::PROTECTED => true,
                null => false,
                default => false
            },
            StatusEnum::PROTECTED => match ($to) {
                StatusEnum::PRIVATE => true,
                StatusEnum::PUBLIC => false,
                default => false
            },
            StatusEnum::PRIVATE => false, //final state
            default => true
        };
    }

$model = new TestModel;
$model->status = StatusEnum::PUBLIC; // OK
$model->save();

$model = TestModel::find(1);
$model->status; // StatusEnum::PUBLIC
$model->status = StatusEnum::PRIVATE; // OK
$model->status = StatusEnum::PUBLIC; // thrown `StatusTransitionDenied`
bash
php artisan vendor:publish --tag="enum-state-machine-migrations"
php artisan migrate