This project implements a flexible and robust state transition system for Laravel models. It allows you to define, apply, and log state transitions for different status fields in your models.
- Define multiple state transitions for different status fields
- Apply state transitions to models
- Log state transition history
- Check for valid transitions
- Retrieve available transitions and states for a model
- Easy integration with existing Laravel models
-
Clone this repository to your local machine:
git clone https://github.com/fadlee/laravel-state-machine.git
-
Install the dependencies:
composer install
-
Run the migrations:
php artisan migrate
Add the HasStateTransitions
trait to your model:
use App\Traits\HasStateTransitions;
class Document extends Model
{
use HasStateTransitions;
// ...
}
Use the StateTransition::register()
method to define state transitions for your model:
use App\Models\Document;
use App\Models\StateTransition;
StateTransition::register(Document::class, [
'submit' => [
'from' => ['pending'],
'to' => 'submitted',
],
'verify' => [
'from' => ['submitted'],
'to' => 'verified',
],
], 'verification_status');
StateTransition::register(Document::class, [
'publish' => [
'from' => ['draft'],
'to' => 'published',
],
'archive' => [
'from' => ['published'],
'to' => 'archived',
],
], 'status');
You can now apply transitions to your model instances:
$document = Document::find(1);
$document->applyTransition('submit', 'verification_status');
$document->applyTransition('publish', 'status');
if ($document->canTransition('verify', 'verification_status')) {
// Apply the transition
}
$availableTransitions = Document::getAvailableTransitions('status');
$availableStates = Document::getAvailableStates('status');
$possibleTransitions = $document->getPossibleTransitions('status');
$transitionLogs = $document->transitionLogs
Run the test suite with:
php artisan test
Contributions are welcome! Please feel free to submit a Pull Request.
This project is open-sourced software licensed under the MIT license.