Created
April 6, 2026 05:39
-
-
Save edgrosvenor/942946332957b070d9949781dd4ed84a to your computer and use it in GitHub Desktop.
Fat Enums: ModelHasStateMachine trait for Eloquent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Models; | |
| use App\Enums\OrderStatus; | |
| use ArtisanBuild\FatEnums\Concerns\ModelHasStateMachine; | |
| use Illuminate\Database\Eloquent\Model; | |
| class Order extends Model | |
| { | |
| use ModelHasStateMachine; | |
| protected $casts = [ | |
| 'status' => OrderStatus::class, | |
| ]; | |
| // Define which columns are state machines | |
| protected array $state_machines = ['status']; | |
| } | |
| // Now transitions are validated automatically on save: | |
| $order = Order::find(1); | |
| $order->status = OrderStatus::Delivered; // Was: Pending | |
| $order->save(); | |
| // InvalidStateTransition thrown BEFORE the database is touched | |
| // "Cannot transition from Pending to Delivered..." | |
| // Valid transitions just work: | |
| $order->status = OrderStatus::Processing; | |
| $order->save(); // Works! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment