PHP code example of rizalsaja / laravel-status-transition
1. Go to this page and download the library: Download rizalsaja/laravel-status-transition 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/ */
rizalsaja / laravel-status-transition example snippets
protected $transitions = [
'pending' => [
'processing' => [
'before' => 'validateStock', // method name
'after' => 'sendProcessingEmail', // method name
],
'cancelled', // no hooks needed — plain string is fine
],
];
public function validateStock(): void
{
// runs before the status is saved
}
public function sendProcessingEmail(): void
{
// runs after the status is saved
}
'cancelled' => [
'after' => function ($model) {
Log::info("Order {$model->id} was cancelled.");
},
],
use Rizalsaja\LaravelStatusTransition\Traits\HasStatus;
class Order extends Model
{
use HasStatus;
/**
* All valid statuses for this model.
*/
protected $statuses = [
'pending',
'processing',
'shipped',
'delivered',
'cancelled',
];
/**
* Allowed transition map.
* Omit this property to allow all transitions freely.
*/
protected $transitions = [
'pending' => ['processing', 'cancelled'],
'processing' => ['shipped', 'cancelled'],
'shipped' => ['delivered'],
'delivered' => [],
'cancelled' => [],
];
}
$table->string('status')->default('pending');
$order = Order::create(['title' => 'New Order']);
// Simple transition
$order->transitionTo('processing');
// With a reason
$order->transitionTo('cancelled', reason: 'Customer requested cancellation');
// All history records (ordered by latest inserted)
$order->statusHistory;
// Most recent record only
$order->latestStatus;
// History fields
$history->from; // 'pending'
$history->to; // 'processing'
$history->reason; // 'Payment confirmed'
$history->changed_by; // user id (nullable)
$history->created_at;
$history = $order->statusHistory->first();
$history->statusable; // returns the Order instance
return [
/*
* Default statuses if the model does not define its own $statuses property.
*/
'default_statuses' => ['active', 'inactive'],
/*
* Set to false to disable status history recording entirely.
*/
'record_history' => true,
];