PHP code example of jobmetric / laravel-state-machine

1. Go to this page and download the library: Download jobmetric/laravel-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/ */

    

jobmetric / laravel-state-machine example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    /**
     * @var array
     */
    protected $fillable = [
        'status',
    ];

    /**
     * @var array
     */
    protected $casts = [
        'status' => 'string',
    ];
}



namespace App\StateMachine;

use Illuminate\Database\Eloquent\Model;
use JobMetric\StateMachine\HasStateMachine;

class OrderStateMachine extends Model
{
    use HasStateMachine;
    
    ...
}



namespace App\StateMachine;

use Illuminate\Database\Eloquent\Model;
use JobMetric\StateMachine\Contracts\StateMachineContract;
use JobMetric\StateMachine\HasStateMachine;

class OrderStateMachine extends Model implements StateMachineContract
{
    use HasStateMachine;
    
    ...
}



namespace App\StateMachine;

use Illuminate\Database\Eloquent\Model;
use JobMetric\StateMachine\Contracts\StateMachineContract;
use JobMetric\StateMachine\HasStateMachine;

class OrderStateMachine extends Model implements StateMachineContract
{
    use HasStateMachine;
    
    ...
    
    public function stateMachineAllowTransition(): void
    {
        $this->allowTransition('status', 'pending', 'processing');
        $this->allowTransition('status', 'processing', 'completed');
    }
}

$order = Order::find(1);

$order->status = 'processing';

$order->save();

$order = Order::find(1);

$order->transitionTo('processing');

php artisan make:state-machine {model} {?state} -f={field}

$common->before();
$exact->before();
// state change
$exact->after();
$common->after();