### Install Laravel Eloquent State Machines Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt Commands to install the package via Composer, publish migrations, and run the migrations to set up the necessary database tables for state tracking. ```bash composer require asantibanez/laravel-eloquent-state-machines php artisan vendor:publish --provider="Asantibanez\LaravelEloquentStateMachines\LaravelEloquentStateMachinesServiceProvider" --tag="migrations" php artisan migrate ``` -------------------------------- ### Perform Basic State Transitions in PHP Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt PHP examples illustrating how to create a model, transition its state, add custom properties to transitions, specify a responsible user, and handle invalid transition exceptions. ```php // Create new order (automatically set to 'pending' state) $salesOrder = SalesOrder::create([ 'total' => 150.00, ]); // Transition to approved state $salesOrder->status()->transitionTo('approved'); // Transition with custom properties $salesOrder->status()->transitionTo('processed', [ 'comments' => 'Customer verified', 'processed_by' => 'John Doe', ]); // Transition with custom responsible user $salesOrder->status()->transitionTo('approved', [], auth()->user()); // Full example with all parameters $salesOrder->status()->transitionTo( $to = 'approved', $customProperties = ['comments' => 'All checks passed'], $responsible = User::find(1) ); // Invalid transition throws TransitionNotAllowedException try { $salesOrder->status()->transitionTo('cancelled'); // Not allowed from 'processed' } catch (TransitionNotAllowedException $e) { // Handle exception } ``` -------------------------------- ### Publish and Run State Machine Migrations Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Publishes the package's migration files and then runs them to prepare the database for state machine history tracking. This is a necessary step after installation. ```bash php artisan vendor:publish --provider="Asantibanez\LaravelEloquentStateMachines\LaravelEloquentStateMachinesServiceProvider" --tag="migrations" php artisan migrate ``` -------------------------------- ### Install Laravel Eloquent State Machines using Composer Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Installs the Laravel Eloquent State Machines package using Composer. This is the primary method for adding the package to your Laravel project. ```bash composer require asantibanez/laravel-eloquent-state-machines ``` -------------------------------- ### Check State and Allowed Transitions in PHP Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt PHP examples demonstrating how to check the current state of a model, verify if a specific transition is allowed, access the state attribute directly, retrieve the responsible user for the current state, and get the current state instance. ```php // Check current state if ($salesOrder->status()->is('approved')) { // Order is approved } if ($salesOrder->status()->isNot('declined')) { // Order is not declined } // Check if transition is allowed if ($salesOrder->status()->canBe('approved')) { $salesOrder->status()->transitionTo('approved'); } // Access state field directly $currentStatus = $salesOrder->status; // 'pending', 'approved', etc. // Get responsible user for current state $responsible = $salesOrder->status()->responsible(); // Returns User|null // Get state instance $stateInstance = $salesOrder->status()->state(); // Returns current state string ``` -------------------------------- ### Manage Multiple Independent State Machines on a Single Eloquent Model Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt This example illustrates how to define and manage multiple, independent state machines on a single Eloquent model. Each state machine ('status', 'fulfillment', 'payment_status') can be transitioned and queried separately. It also shows how to query models based on the states of these multiple machines. ```php class SalesOrder extends Model { use HasStateMachines; public $stateMachines = [ 'status' => StatusStateMachine::class, 'fulfillment' => FulfillmentStateMachine::class, 'payment_status' => PaymentStatusStateMachine::class, ]; } // Each state machine operates independently $salesOrder->status()->transitionTo('approved'); $salesOrder->fulfillment()->transitionTo('pending'); $salesOrder->paymentStatus()->transitionTo('paid'); // Auto converts to camelCase // Check states if ($salesOrder->status()->is('approved') && $salesOrder->fulfillment()->is('completed')) { // Order approved and fulfilled } // Query history for each state machine $statusHistory = $salesOrder->status()->history()->get(); $fulfillmentHistory = $salesOrder->fulfillment()->history()->get(); // Query models by multiple state machines $orders = SalesOrder::whereHasStatus(function ($query) { $query->transitionedTo('approved'); })->whereHasFulfillment(function ($query) { $query->transitionedTo('completed'); })->whereHasPaymentStatus(function ($query) { $query->transitionedTo('paid'); })->get(); ``` -------------------------------- ### Tracking Attribute Changes During State Transitions in Laravel Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md When `recordHistory()` is active, track attribute changes during state transitions. Use `changedAttributesNames()` to get an array of changed attribute names. Then, use `changedAttributeOldValue($attributeName)` and `changedAttributeNewValue($attributeName)` to retrieve the old and new values of specific attributes. ```php $salesOrder = SalesOrder::create([ 'total' => 100, ]); $salesOrder->total = 200; $salesOrder->status()->transitionTo('approved'); $salesOrder->changedAttributesNames(); // ['total'] $salesOrder->changedAttributeOldValue('total'); // 100 $salesOrder->changedAttributeNewValue('total'); // 200 ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Execute the project's test suite using Composer. This command runs all defined tests to ensure the code functions as expected. ```bash composer test ``` -------------------------------- ### Transition Eloquent Model States Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Demonstrates how to transition an Eloquent model's state using the state machine. Supports transitions with custom properties and a specified responsible party. ```php $salesOrder->status()->transitionTo('approved'); $salesOrder->fulfillment()->transitionTo('completed'); //With custom properties $salesOrder->status()->transitionTo('approved', [ 'comments' => 'Customer has available credit', ]); //With responsible $salesOrder->status()->transitionTo('approved', [], $responsible); // auth()->user() by default ``` -------------------------------- ### Define State Machine Logic in PHP Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt PHP code demonstrating how to define a custom state machine by extending the base StateMachine class. It includes configurations for history recording, allowed transitions between states, and the default initial state. ```php use AsantibanezLaravelEloquentStateMachinesStateMachines\StateMachine; class StatusStateMachine extends StateMachine { public function recordHistory(): bool { return true; // Enable automatic history tracking } public function transitions(): array { return [ 'pending' => ['approved', 'declined'], 'approved' => ['processed'], 'declined' => [], // Terminal state ]; } public function defaultState(): ?string { return 'pending'; // Initial state for new models } } ``` -------------------------------- ### Generate State Machine Class with Artisan Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt Artisan command to generate a boilerplate StateMachine class, which serves as the foundation for defining state transition logic. ```bash php artisan make:state-machine StatusStateMachine ``` -------------------------------- ### Add Before and After Transition Hooks in PHP Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt Define custom logic to be executed before and after state transitions. 'beforeTransitionHooks' use the 'from' state as the key, allowing actions before leaving a state, while 'afterTransitionHooks' use the 'to' state, enabling actions upon entering a new state. ```php use Illuminate\Support\Facades\Mail; use App\Jobs\ProcessPayment; use App\Mail\OrderApproved; class StatusStateMachine extends StateMachine { // ... other methods ... // Before hooks use $from state as key public function beforeTransitionHooks(): array { return [ 'pending' => [ function ($to, $model) { // Executed BEFORE transitioning FROM pending logger()->info("About to transition from pending to {$to}"); }, function ($to, $model) { if ($to === 'approved') { // Prepare model before approval $model->approved_at = now(); } }, ], 'approved' => [ function ($to, $model) { // Cleanup before leaving approved state logger()->info("Leaving approved state to {$to}"); }, ], ]; } // After hooks use $to state as key public function afterTransitionHooks(): array { return [ 'approved' => [ function ($from, $model) { // Executed AFTER transitioning TO approved Mail::to($model->customer->email)->send(new OrderApproved($model)); }, function ($from, $model) { // Dispatch notification job \App\Jobs\SendApprovalNotification::dispatch($model); }, ], 'processed' => [ function ($from, $model) { // Process payment after order is processed ProcessPayment::dispatch($model); }, function ($from, $model) { // Update inventory $model->decrementInventory(); }, ], ]; } } ``` -------------------------------- ### Define Wildcard Transitions in State Machine Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Illustrates the use of wildcards ('*') for defining flexible transitions in a StateMachine. Wildcards can represent any current state or any possible next state, simplifying complex transition rules. ```php public function transitions(): array { return [ '*' => ['approved', 'declined'], // From any to 'approved' or 'declined' 'approved' => '*', // From 'approved' to any '*' => '*', // From any to any ]; } ``` -------------------------------- ### Use Wildcard Transitions in PHP Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt Define flexible transition rules using wildcard characters. A '*' can represent any state, allowing for simplified configuration where transitions apply from or to multiple states simultaneously. This can be combined with specific state rules. ```php class StatusStateMachine extends StateMachine { public function transitions(): array { return [ // From any state to cancelled '*' => ['cancelled'], // From approved to any state 'approved' => '*', // Can combine with specific rules 'pending' => ['approved', 'declined'], 'approved' => ['processed', 'on_hold'], // This overrides '*' above // Any state to any state (completely open) '*' => '*', ]; } } // Usage $salesOrder->status()->transitionTo('cancelled'); // Works from any state due to '*' => ['cancelled'] ``` -------------------------------- ### Query Models by State History using Eloquent State Machines Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt This code demonstrates how to query Eloquent models based on their state history using the `whereHasStatus` method provided by the package. It covers filtering models by specific transitions, responsible users, custom properties within states, and even combining queries across multiple state machines or states. ```php // Find all sales orders that transitioned from pending to approved $orders = SalesOrder::whereHasStatus(function ($query) { $query->withTransition('pending', 'approved'); })->get(); // Find orders approved by a specific user $orders = SalesOrder::whereHasStatus(function ($query) { $query ->transitionedTo('approved') ->withResponsible(auth()->user()); })->get(); // Find orders with specific custom properties $orders = SalesOrder::whereHasStatus(function ($query) { $query ->transitionedTo('approved') ->withCustomProperty('credit_score', '>=', 700); })->get(); // Combine multiple state machines $orders = SalesOrder::whereHasStatus(function ($query) { $query->transitionedTo(['approved', 'processed']); }) ->whereHasFulfillment(function ($query) { // Assuming another state machine on Fulfillment model $query->transitionedTo('completed'); }) ->get(); // Query from multiple states $orders = SalesOrder::whereHasStatus(function ($query) { $query->withTransition(['pending', 'waiting'], ['approved', 'declined']); })->get(); ``` -------------------------------- ### Add Before and After Transition Hooks (PHP) Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Implement `beforeTransitionHooks` and `afterTransitionHooks` to execute custom callbacks before or after state transitions. These methods should return an associative array where keys are states and values are arrays of callbacks or closures. ```php class StatusStateMachine extends StateMachine { public function beforeTransitionHooks(): array { return [ 'approved' => [ function ($to, $model) { // Dispatch some job BEFORE "approved changes to $to" }, function ($to, $model) { // Send mail BEFORE "approved changes to $to" }, ], ]; } public function afterTransitionHooks() { return [ 'processed' => [ function ($from, $model) { // Dispatch some job AFTER "$from transitioned to processed" }, function ($from, $model) { // Send mail AFTER "$from transitioned to processed" }, ], ]; } } ``` -------------------------------- ### Basic State Machine Class Definition Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Defines a basic StateMachine class structure. It includes methods to control history recording, define allowed transitions, and set a default state for the model. ```php use Asantibanez\LaravelEloquentStateMachines\StateMachines\StateMachine; class StatusStateMachine extends StateMachine { public function recordHistory(): bool { return false; } public function transitions(): array { return [ // ]; } public function defaultState(): ?string { return null; } } ``` -------------------------------- ### Query State History with Eloquent State Machines Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt This snippet demonstrates how to query the state history of a model using the Eloquent State Machines package. It covers checking if a model was ever in a specific state, counting state occurrences, retrieving timestamps, accessing state snapshots, and querying the full history with custom filters. Dependencies include the package itself and Carbon for timestamps. ```php // Check if model was ever in a state $wasApproved = $salesOrder->status()->was('approved'); // true/false // Count how many times model was in a state $timesApproved = $salesOrder->status()->timesWas('approved'); // int // Get timestamp when model entered a state $whenApproved = $salesOrder->status()->whenWas('approved'); // Carbon|null // Get latest snapshot for a state $snapshot = $salesOrder->status()->snapshotWhen('approved'); // StateHistory|null if ($snapshot) { $comments = $snapshot->getCustomProperty('comments'); $responsible = $snapshot->responsible; $timestamp = $snapshot->created_at; } // Get all snapshots for a state $allApprovedSnapshots = $salesOrder->status()->snapshotsWhen('approved'); // Collection // Get full history with query builder $history = $salesOrder->status()->history() ->from('pending') ->to('approved') ->withCustomProperty('comments', 'like', '%verified%') ->withResponsible(auth()->user()) ->get(); // Each history record contains: field, from, to, custom_properties, responsible, created_at foreach ($history as $record) { echo "Transitioned from {$record->from} to {$record->to} at {$record->created_at}"; } ``` -------------------------------- ### Access Custom Properties and Responsible Users with Eloquent State Machines Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt This section illustrates how to manage and access custom properties and responsible users during state transitions. It shows how to pass custom data during a transition, retrieve specific custom properties or all of them from the current or previous states, and access the responsible user associated with a state. ```php // Transition with custom properties $salesOrder->status()->transitionTo('approved', [ 'comments' => 'Credit check passed', 'credit_score' => 750, 'approved_amount' => 5000, ]); // Get custom property from current state $comments = $salesOrder->status()->getCustomProperty('comments'); $creditScore = $salesOrder->status()->getCustomProperty('credit_score'); // Get all custom properties from current state $allProperties = $salesOrder->status()->allCustomProperties(); // Get custom properties from previous state $previousSnapshot = $salesOrder->status()->snapshotWhen('pending'); $pendingComments = $previousSnapshot?->getCustomProperty('comments'); // Get responsible user from current state $responsible = $salesOrder->status()->responsible(); // User|null // Get responsible user from previous state $approver = $salesOrder->status()->snapshotWhen('approved')?->responsible; ``` -------------------------------- ### Transition State Using StateMachine Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Applies a state transition to a model's state field using the `transitionTo` method. This method attempts to move the state to the specified value, respecting defined transitions. ```php $salesOrder->status()->transitionTo($to = 'approved'); ``` -------------------------------- ### Add Transition Validations in PHP Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt Implement custom validation logic before a state transition occurs. This method allows defining specific validation rules based on the 'from' and 'to' states, ensuring data integrity. It returns a Laravel Validator instance or null if no validation is needed. ```php use Illuminate\Support\Facades\Validator as ValidatorFacade; use Illuminate\Contracts\Validation\Validator; class StatusStateMachine extends StateMachine { // ... other methods ... public function validatorForTransition($from, $to, $model): ?Validator { // Validate before approving if ($from === 'pending' && $to === 'approved') { return ValidatorFacade::make([ 'total' => $model->total, 'customer_id' => $model->customer_id, ], [ 'total' => 'required|numeric|gt:0', 'customer_id' => 'required|exists:customers,id', ]); } // Validate before processing if ($from === 'approved' && $to === 'processed') { return ValidatorFacade::make([ 'payment_confirmed' => $model->payment_confirmed, ], [ 'payment_confirmed' => 'required|boolean|accepted', ]); } return parent::validatorForTransition($from, $to, $model); } } // Usage - ValidationException thrown if validation fails try { $salesOrder->status()->transitionTo('approved'); } catch (ValidationException $e) { $errors = $e->errors(); // ['total' => ['The total must be greater than 0']] } ``` -------------------------------- ### Define Allowed Transitions in State Machine Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Specifies the allowed transitions between states within a StateMachine. This method returns an array where keys are current states and values are arrays of possible next states. ```php public function transitions(): array { return [ 'pending' => ['approved', 'declined'], 'approved' => ['processed'], ]; } ``` -------------------------------- ### Track Attribute Changes During Transitions with Eloquent State Machines Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt This snippet explains how the Eloquent State Machines package tracks attribute changes on a model during state transitions. It shows how to transition a model, then retrieve the names of changed attributes, and access their old and new values from the state snapshot. ```php // Create and modify model $salesOrder = SalesOrder::create(['total' => 100, 'items_count' => 5]); $salesOrder->total = 200; $salesOrder->items_count = 10; // Transition saves changed attributes $salesOrder->status()->transitionTo('approved'); // Get changed attribute names $changedAttributes = $salesOrder->status()->latest()->changedAttributesNames(); // Returns: ['total', 'items_count'] // Get old and new values $snapshot = $salesOrder->status()->latest(); $oldTotal = $snapshot->changedAttributeOldValue('total'); // 100 $newTotal = $snapshot->changedAttributeNewValue('total'); // 200 $oldCount = $snapshot->changedAttributeOldValue('items_count'); // 5 $newCount = $snapshot->changedAttributeNewValue('items_count'); // 10 ``` -------------------------------- ### Retrieving Custom Properties of State Transitions in Laravel Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Access custom properties associated with state transitions using the `getCustomProperty($key)` method. This method retrieves properties for the current state. For properties of previous states, use the `snapshotWhen($state)` method followed by `getCustomProperty()`. ```php $salesOrder->status()->getCustomProperty('comments'); $salesOrder->status()->snapshotWhen('approved')->getCustomProperty('comments'); ``` -------------------------------- ### Schedule State Transitions for Future Execution Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt This snippet demonstrates how to schedule a state transition to occur at a specified future time using Carbon for date manipulation. It also shows how to check for and retrieve pending transitions, and how to cancel all scheduled transitions. A cron job is required to dispatch the pending transitions. ```php use Carbon\Carbon; // Schedule transition for later $salesOrder->status()->postponeTransitionTo( $state = 'processed', $when = Carbon::now()->addDays(3), $customProperties = ['auto_processed' => true], $responsible = auth()->user() ); // Check if model has pending transitions if ($salesOrder->status()->hasPendingTransitions()) { $pending = $salesOrder->status()->pendingTransitions()->notApplied()->get(); foreach ($pending as $transition) { echo "Scheduled transition from {$transition->from} to {$transition->to} at {$transition->transition_at}"; } } // Schedule the dispatcher job in app/Console/Kernel.php protected function schedule(Schedule $schedule) { $schedule->job(Asantibanez\LaravelEloquentStateMachines\Jobs\PendingTransitionsDispatcher::class) ->everyMinute(); // Or ->everyFiveMinutes(), ->everyTenMinutes() } // Cancel all pending transitions for a state $salesOrder->status()->stateMachine()->cancelAllPendingTransitions(); ``` -------------------------------- ### Schedule Pending Transitions Dispatcher (PHP) Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Schedule the `PendingTransitionsDispatcher` job to run periodically (e.g., every minute) to process postponed state transitions. This ensures that transitions saved in the `pending_transitions` table are applied at their scheduled times. ```php $schedule->job(PendingTransitionsDispatcher::class)->everyMinute(); ``` -------------------------------- ### Transition State with Custom Properties Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Performs a state transition while also passing custom properties to be associated with the transition event. These properties can include additional data relevant to the state change. ```php $salesOrder->status()->transitionTo($to = 'approved', $customProperties = [ 'comments' => 'All ready to go' ]); ``` -------------------------------- ### Querying State History in Laravel Eloquent Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Record state transitions using `recordHistory()` and query the history using methods like `was()`, `timesWas()`, `whenWas()`, `snapshotWhen()`, `snapshotsWhen()`, and `history()`. The `history()` method returns an Eloquent relationship that can be further filtered using scopes like `from()`, `to()`, and `withCustomProperty()`. ```php $salesOrder->status()->was('approved'); // true or false $salesOrder->status()->timesWas('approved'); // int $salesOrder->status()->whenWas('approved'); // ?Carbon $salesOrder->status()->snapshotWhen('approved'); $salesOrder->status()->snapshotsWhen('approved'); $salesOrder->status()->history()->get(); $salesOrder->status()->history() ->from('pending') ->to('approved') ->withCustomProperty('comments', 'like', '%good%') ->get(); ``` -------------------------------- ### Register State Machine in Eloquent Model Source: https://context7.com/asantibanez/laravel-eloquent-state-machines/llms.txt PHP code showing how to integrate a state machine into a Laravel Eloquent model using the `HasStateMachines` trait. This defines which attributes in the model will be managed by state machines and maps them to their respective StateMachine classes. ```php use Asantibanez\LaravelEloquentStateMachines\Traits\HasStateMachines; use Illuminate\Database\Eloquent\Model; class SalesOrder extends Model { use HasStateMachines; protected $guarded = []; public $stateMachines = [ 'status' => StatusStateMachine::class, 'fulfillment' => FulfillmentStateMachine::class, ]; } ``` -------------------------------- ### Enable State Transition History Recording Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Enables automatic recording of state transitions performed by the state machine. Setting this method to return true ensures that each state change is logged. ```php public function recordHistory(): bool { return true; } ``` -------------------------------- ### Transition State with Responsible User Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Executes a state transition and specifies the user responsible for the action. If not provided, the system defaults to `auth()->user()`. This allows for auditing and tracking of state changes. ```php $salesOrder->status()->transitionTo( $to = 'approved', $customProperties = [], $responsible = User::first() ); ``` -------------------------------- ### Query Eloquent Model State Transition History Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Retrieves the history of state transitions for an Eloquent model. Allows checking past states, the number of times a state was held, and when it occurred. ```php $salesOrder->status()->was('approved'); $salesOrder->status()->timesWas('approved'); $salesOrder->status()->whenWas('approved'); $salesOrder->fulfillment()->snapshotWhen('completed'); $salesOrder->status()->history()->get(); ``` -------------------------------- ### Add State Transition Validations (PHP) Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Override the `validatorForTransition` method to define custom validation logic before a state transition occurs. This method should return a Laravel Validator instance. If the validator fails, a ValidationException is thrown, preventing the transition. ```php use Illuminate\Support\Facades\Validator as ValidatorFacade; class StatusStateMachine extends StateMachine { public function validatorForTransition($from, $to, $model): ?Validator { if ($from === 'pending' && $to === 'approved') { return ValidatorFacade::make([ 'total' => $model->total, ], [ 'total' => 'gt:0', ]); } return parent::validatorForTransition($from, $to, $model); } } ``` -------------------------------- ### Set Default State in State Machine Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Sets the initial or default state for the state machine. This method returns the name of the default state as a string, or null if no default state is desired. ```php public function defaultState(): ?string { return 'pending'; // it can be null too } ``` -------------------------------- ### Check for Pending Transitions (PHP) Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Use the `hasPendingTransitions()` method on a model's state machine instance to determine if there are any pending transitions for that specific state machine. This is useful for checking the status of postponed transitions. ```php $salesOrder->status()->hasPendingTransitions(); ``` -------------------------------- ### Register State Machine in Eloquent Model Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Registers a StateMachine with a specific field in a Laravel Eloquent model. The `$stateMachines` attribute maps a model field (e.g., 'status') to its corresponding StateMachine class. ```php use Asantibanez\LaravelEloquentStateMachines\Traits\HasStateMachines; use App\StateMachines\StatusStateMachine; class SalesOrder extends Model { Use HasStateMachines; public $stateMachines = [ 'status' => StatusStateMachine::class ]; } ``` -------------------------------- ### Check Available Transitions for Eloquent Model State Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Checks if a specific transition is allowed for the current state of an Eloquent model. Returns a boolean indicating if the transition can be made. ```php $salesOrder->status()->canBe('approved'); $salesOrder->status()->canBe('declined'); ``` -------------------------------- ### Retrieving the Responsible Party of State Transitions in Laravel Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Obtain the `$responsible` object that applied a state transition using the `responsible()` method. This method returns the responsible party for the current state. For previous states, use `snapshotWhen($state)` and access the `responsible` property. Note that `responsible` can be `null` in background jobs. ```php $salesOrder->status()->responsible(); $salesOrder->status()->snapshotWhen('approved')->responsible; ``` -------------------------------- ### Querying Models Based on State History in Laravel Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Utilize the `whereHas{FIELD_NAME}` method introduced by the `HasStateMachines` trait to filter model queries based on state transitions, responsible parties, and custom properties. This method accepts a closure with constraints like `withTransition()`, `transitionedFrom()`, `transitionedTo()`, `withResponsible()`, and `withCustomProperty()`. ```php SalesOrder::with() ->whereHasStatus(function ($query) { $query ->withTransition('pending', 'approved') ->withResponsible(auth()->id()) ; }) ->whereHasFulfillment(function ($query) { $query ->transitionedTo('complete') ; }) ->get(); ``` -------------------------------- ### Check Current and Responsible State for Eloquent Model Source: https://github.com/asantibanez/laravel-eloquent-state-machines/blob/master/README.md Checks if an Eloquent model is currently in a specific state or retrieves the user responsible for the last state change. Returns a boolean or a User object/null. ```php $salesOrder->status()->is('approved'); $salesOrder->status()->responsible(); // User|null ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.