aventure-cloud / eloquent-status-recorder
Eloquent model's status management with history
Requires
- php: >=7.0.0
- illuminate/database: ^5.5
- illuminate/support: ^5.5
Requires (Dev)
- fzaninotto/faker: ^1.6
- mockery/mockery: ^0.9.5
- phpunit/phpunit: ^5.5
This package is auto-updated.
Last update: 2024-11-28 01:29:01 UTC
README
Any eloquent model can have Status management with just one trait. Declare status statically but store status history four your models in the database.
- Author: Valerio Barbera - valerio@aventuresrl.com
- Author Website: www.aventuresrl.com
Install
composer require aventure-cloud/eloquent-status-recorder
Config
Publish configuration file in your project:
php artisan vendor:publish --provider="AventureCloud\EloquentStatusRecorder\EloquentStatusRecorderServiceProvider" --tag="config"
Migration
We provide a migration script to create statuses
table.
To publish migration script execute:
php artisan vendor:publish --provider="AventureCloud\EloquentStatusRecorder\EloquentStatusRecorderServiceProvider" --tag="migrations"
And run with artisan command:
php artisan migrate --path=/database/migrations
Use
Attach HasStatus
trait to your models and configure statuses values
for each models indipendently.
class Order extends Model { use HasStatus; protected $statuses = [ 'opened' => [], 'paid' => ['from' => 'opened'], 'approved' => ['from' => 'paid'], 'shipped' => ['from' => ['paid', 'approved']], 'arrived' => ['from' => 'shipped'], 'cancelled' => ['not-from' => ['arrived']], ]; }
Utility methods
$order = Order::find(1); /* * Current status * instance of model configured in config('eloquent-status-recorder.status_model') */ $order->status; /* * List of all available statuses for current model */ $order->statuses(); /* * Available statuses after current status value based on "from" and "not-from" rules */ $order->nextAvailableStatuses(); /* * Change status */ $order->changeStatusTo('shipped');
Auto-run callbacks
In some cases, you need to do something after a specific status is set.
For example, send an mail after an order is "shipped". This package
invokes a method after status change by the convention of
on + status_name (camel cased)
:
class Order extends Model { use HasStatus; protected $statuses = [ 'opened' => [], 'paid' => ['from' => 'opened'], 'approved' => ['from' => 'paid'], 'shipped' => ['from' => ['paid', 'approved']], 'arrived' => ['from' => 'shipped'], 'cancelled' => ['not-from' => ['arrived']], ]; public function onShipped() { // Send email to the user } }
Events
Every time a status change happen two event will fire with attached the current eloquent model instance and the given status:
- StatusChanging (Before status is saved)
- StatusChanged (After status change is performed)