### Install Utilitarian Laravel Toolkit Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Install the package using Composer, publish configuration files, and run migrations for the state machine. ```bash composer require utilitarian-dev/utilitarian-laravel-toolkit # Publish config (optional) php artisan vendor:publish --tag=utilitarian-config # Run migrations (required for State Machine) php artisan migrate ``` -------------------------------- ### Install Utilitarian Laravel Toolkit Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Install the package using Composer. The service provider is automatically registered. ```bash composer require utilitarian-dev/utilitarian-laravel-toolkit ``` -------------------------------- ### Run Database Migrations Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Execute database migrations to set up the necessary tables for the application. This command should be run after initial setup or when deploying changes. ```bash php artisan migrate ``` -------------------------------- ### Transition to Enum States Freely Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Transition to any enum state without predefined rules. State is persisted and can be inspected. This example shows basic transitions and checks. ```php enum OrderStatus: string { case Pending = 'pending'; case Paid = 'paid'; case Shipped = 'shipped'; case Canceled = 'canceled'; } $order->state()->transitionTo(OrderStatus::Paid); $order->state()->current(); // OrderStatus::Paid $order->state()->is(OrderStatus::Paid); // true $order->state()->in(OrderStatus::Paid, OrderStatus::Shipped); // true // Attach extra data on transition $order->state()->transitionTo(OrderStatus::Shipped, [ 'tracking_number' => 'TRK-12345', 'shipped_by' => 'FedEx', ]); ``` -------------------------------- ### Install LaraDumps for Optional Driver Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/src/Debug/README.md Install LaraDumps as a development dependency if you plan to use the 'laradumps' driver. ```bash composer require laradumps/laradumps --dev ``` -------------------------------- ### Use HasStateMachine Trait for Eloquent Models Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Add the `HasStateMachine` trait to any Eloquent model to gain a `state()` accessor. State records are stored polymorphically and deleted automatically with the model. This example demonstrates key-value storage for state. ```php use Illuminate\Database\Eloquent\Model; use Utilitarian\StateMachine\Traits\HasStateMachine; class Order extends Model { use HasStateMachine; } // Key-value storage (no enum required) $order->state()->set('notes', 'Handle with care'); $order->state()->set('metadata.source', 'api'); echo $order->state()->get('notes'); // 'Handle with care' echo $order->state()->get('metadata.source'); // 'api' $order->state()->has('notes'); // true $order->state()->forget('notes'); $all = $order->state()->all(); // ['metadata' => ['source' => 'api']] $order->state()->clear(); // wipe all data ``` -------------------------------- ### Dependency Injection in Commands Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Inject runtime dependencies into a Command's `boot()` method. The `SearchIndexClient` must be resolvable by the service container. ```php class SyncProductToSearchIndexCommand extends Command { private SearchIndexClient $search; public function __construct( private readonly Product $product, ) {} public function boot(SearchIndexClient $search): void { $this->search = $search; } public function execute(): void { $this->search->index('products', [ 'id' => $this->product->id, 'name' => $this->product->name, ]); } } ``` -------------------------------- ### Publish Configuration Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Optionally, publish the configuration file for Utilitarian Laravel Toolkit. ```bash php artisan vendor:publish --tag=utilitarian-config ``` -------------------------------- ### Define and Execute a Command Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Define a write-only Command operation and execute it using `dispatch()`. Ensure the `User` model and database table exist. ```php class CreateUserCommand extends Command { public function __construct( private readonly string $email, private readonly string $name, ) {} public function execute(): User { return User::query()->create([ 'email' => $this->email, 'name' => $this->name, ]); } } // Execute $user = CreateUserCommand::make(email: '...', name: '...')->dispatch(); ``` -------------------------------- ### Transition Enum States (no rules) Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Demonstrates basic state transitions and checks using an enum without defined transition rules. Ensure the state enum implements the necessary interfaces for state management. ```php $order->state()->transitionTo(OrderState::Paid); $order->state()->current(); // OrderState::Paid $order->state()->is(OrderState::Paid); // true ``` -------------------------------- ### Run Tests and Coverage Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Commands for executing the test suite and generating code coverage reports. Use `composer test` for standard runs and `composer test:coverage` for detailed coverage analysis. ```bash composer test # Run tests composer test:coverage # Run with coverage ``` -------------------------------- ### Define and Dispatch a Query Operation Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Extend the Query base class for read operations. Inject dependencies in `boot()` and implement `execute()`. Dispatch using `->dispatch()` or `QueryBus::execute()`. ```php use Utilitarian\Cqrs\Query; use Utilitarian\Facades\QueryBus; class GetActiveUsersQuery extends Query { private UserRepository $repo; public function __construct( private readonly string $role, private readonly int $limit = 20, ) {} // Optional: inject runtime dependencies public function boot(UserRepository $repo): void { $this->repo = $repo; } public function execute(): \Illuminate\Support\Collection { return $this->repo->activeByRole($this->role, $this->limit); } } // Fluent API $users = GetActiveUsersQuery::make(role: 'editor', limit: 10)->dispatch(); // Explicit bus $users = QueryBus::execute(GetActiveUsersQuery::make(role: 'editor')); ``` -------------------------------- ### Configure CQRS Middleware Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Configure global middleware for Query, Command, and Action buses in `config/utilitarian.php`. Ensure middleware classes are correctly namespaced. ```php return [ 'cqrs' => [ 'query_middleware' => [ \Utilitarian\Cqrs\Middleware\CachingMiddleware::class, ], 'command_middleware' => [ \Utilitarian\Cqrs\Middleware\TransactionMiddleware::class, ], 'action_middleware' => [ \Utilitarian\Cqrs\Middleware\AuthorizationMiddleware::class, ], ], ]; ``` -------------------------------- ### Basic Debug Usage Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/src/Debug/README.md Use the debug helper to dump values or switch drivers for logging. ```php debug()->dump($value); debug()->driver('log')->dump($value); Debug::dump($value); ``` -------------------------------- ### Define and Execute an Action Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Define an Action for business logic and orchestration, executing other Commands or Actions. Execute using `dispatch()` or `ActionBus::execute()`. Ensure related Commands like `SendWelcomeEmailCommand` are defined. ```php class RegisterUserAction extends Action { public function __construct( private readonly string $email, private readonly string $name, ) {} public function execute(): User { $user = CreateUserCommand::make( email: $this->email, name: $this->name )->dispatch(); SendWelcomeEmailCommand::make(userId: $user->id)->dispatch(); return $user; } } // Execute $user = RegisterUserAction::make(email: '...', name: '...')->dispatch(); // or $user = ActionBus::execute(RegisterUserAction::make(email: '...', name: '...')); ``` -------------------------------- ### Log Command/Query Execution and Failures Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Integrate LoggingMiddleware to log the execution of commands and queries using Laravel's LoggerInterface. It logs 'info' before and after execution, and 'error' with a full trace upon failure. ```php use Utilitarian\Cqrs\Query; use Utilitarian\Cqrs\Middleware\LoggingMiddleware; class SearchProductsQuery extends Query { public function __construct(private readonly string $term) {} public function middleware(): array { return [LoggingMiddleware::class]; } public function execute(): \Illuminate\Support\Collection { return Product::where('name', 'like', "%{$this->term}%")->get(); } } // Logs: // [info] Executing Query: App\Queries\SearchProductsQuery // [info] Completed Query: App\Queries\SearchProductsQuery // On failure: // [error] Failed Query: App\Queries\SearchProductsQuery {"error":"...","trace":"..."} $products = SearchProductsQuery::make(term: 'widget')->dispatch(); ``` -------------------------------- ### Define and Execute a Query Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Define a read-only Query operation and execute it using `dispatch()` or `QueryBus::execute()`. Ensure the `User` model and database table exist. ```php class GetUserQuery extends Query { public function __construct( private readonly int $userId, ) {} public function execute(): ?User { return User::query()->find($this->userId); } } // Execute $user = GetUserQuery::make(userId: 1)->dispatch(); // or $user = QueryBus::execute(GetUserQuery::make(userId: 1)); ``` -------------------------------- ### Environment-Aware Debugging with Debug Facade Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt The Debug facade offers environment-aware debugging output with swappable drivers like 'laravel', 'log', 'laradumps', and 'silent-log'. Debugging is controlled by configuration or feature flags. It allows dumping variables and accessing specific drivers like LaraDumps. ```php use Utilitarian\Facades\Debug; // Check mode if (Debug::isEnabled()) { Debug::dump($someValue); } // Proxy to default driver (laravel or log) Debug::dump(['key' => 'value', 'items' => [1, 2, 3]]); // Use LaraDumps driver explicitly Debug::driver('laradumps')->dump($query->toSql()); // Access raw LaraDumps instance Debug::ds()->label('My Query')->dump($query->toSql()); // Global helper debug()->dump($value); debug()->driver('log')->dump($value); ``` -------------------------------- ### Per-Class and Runtime Middleware Configuration Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Operations can override 'middleware()' to add class-level middleware and 'excludeMiddleware()' to suppress inherited ones. 'withMiddleware()' and 'withoutMiddleware()' apply to a single instance at call time. ```php use Utilitarian\Cqrs\Query; use Utilitarian\Cqrs\Middleware\CachingMiddleware; use Utilitarian\Cqrs\Middleware\LoggingMiddleware; class GetProductQuery extends Query { public function __construct(private readonly int $id) {} // Always applied to this class public function middleware(): array { return [CachingMiddleware::class]; } // Remove from inherited global stack public function excludeMiddleware(): array { return [LoggingMiddleware::class]; } public function cacheKey(): string { return "product:{ $this->id }"; } public function cacheTtl(): int { return 3600; } public function execute(): ?Product { return Product::find($this->id); } } // Runtime override — add extra middleware for this one call only $product = GetProductQuery::make(id: 42) ->withMiddleware(new CustomAuditMiddleware()) ->dispatch(); ``` -------------------------------- ### Publish Debug Configuration Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/src/Debug/README.md Publish the debug configuration file to your project. ```bash php artisan vendor:publish --tag=debug-config ``` -------------------------------- ### Operation Static Factory and Dispatch Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Uses a static 'make()' factory to forward named arguments to the constructor, enabling fluent calls. Supports chaining with middleware control before dispatching. ```php // Named arguments forwarded to __construct $query = GetActiveUsersQuery::make(role: 'admin', limit: 5); // Positional arguments also work $command = CreateOrderCommand::make(1, [['product_id' => 3, 'price' => 9.99]]); // Chain with middleware control then dispatch $result = SomeCommand::make(value: 'x') ->withMiddleware(LoggingMiddleware::class) ->withoutMiddleware(TransactionMiddleware::class) ->dispatch(); ``` -------------------------------- ### Define and Dispatch a Command Operation Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Extend the Command base class for write operations. Use `TransactionMiddleware` for state-mutating work. Dispatch using `->dispatch()` or `CommandBus::execute()`. ```php use Utilitarian\Cqrs\Command; use Utilitarian\Facades\CommandBus; use Illuminate\Contracts\Events\Dispatcher; class CreateOrderCommand extends Command { private Dispatcher $events; public function __construct( private readonly int $userId, private readonly array $items, ) {} public function boot(Dispatcher $events): void { $this->events = $events; } public function execute(): Order { $order = Order::query()->create([ 'user_id' => $this->userId, 'total' => collect($this->items)->sum('price'), ]); foreach ($this->items as $item) { $order->lines()->create($item); } $this->events->dispatch(new OrderCreated($order)); return $order; } } // Fluent $order = CreateOrderCommand::make( userId: auth()->id(), items: [['product_id' => 5, 'price' => 49.99]] )->dispatch(); // Via bus $order = CommandBus::execute( CreateOrderCommand::make(userId: 1, items: []) ); ``` -------------------------------- ### Implement Custom Middleware in Laravel Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Implement the `Middleware` contract to create custom middleware. The `handle()` method receives the operation and a `$next` closure. Ensure the `RateLimitMiddleware` is applied per-class or globally as needed. ```php use Closure; use Utilitarian\Cqrs\Contracts\Middleware; use Utilitarian\Cqrs\Operation; class RateLimitMiddleware implements Middleware { public function __construct( private readonly \Illuminate\Cache\RateLimiter $limiter ) {} public function handle(Operation $operation, Closure $next): mixed { $key = 'op:' . get_class($operation) . ':' . auth()->id(); if ($this->limiter->tooManyAttempts($key, maxAttempts: 10)) { throw new \RuntimeException('Rate limit exceeded.'); } $this->limiter->hit($key, decaySeconds: 60); return $next($operation); } } // Apply per-class class PlaceOrderAction extends Action { public function middleware(): array { return [RateLimitMiddleware::class]; } // ... } ``` -------------------------------- ### Global Middleware Configuration Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Declares global middleware in 'config/utilitarian.php' that applies to all operations of each type (query, command, action). ```php // config/utilitarian.php return [ 'cqrs' => [ 'query_middleware' => [ \Utilitarian\Cqrs\Middleware\CachingMiddleware::class, \Utilitarian\Cqrs\Middleware\LoggingMiddleware::class, ], 'command_middleware' => [ \Utilitarian\Cqrs\Middleware\TransactionMiddleware::class, \Utilitarian\Cqrs\Middleware\ValidationMiddleware::class, ], 'action_middleware' => [ \Utilitarian\Cqrs\Middleware\AuthorizationMiddleware::class, \Utilitarian\Cqrs\Middleware\EventMiddleware::class, ], ], ]; ``` -------------------------------- ### JSON Encoding, Decoding, and Validation with Json Facade Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt The Json facade provides methods for encoding and decoding JSON strings, including safe decoding with a default value. It also offers validation and content-addressable hashing. Drivers like 'pretty' can be specified for different output formats. ```php use Utilitarian\Facades\Json; // Encode / decode $encoded = Json::encode(['name' => 'Ada', 'score' => 100]); // '{"name":"Ada","score":100}' $decoded = Json::decode($encoded); // ['name' => 'Ada', 'score' => 100] // Safe decode (returns default on failure) $value = Json::tryDecode('not valid json', default: []); // [] // Validate Json::validate('{"valid":true}'); // true Json::validate('{"broken":'); // false // Content-addressable hash $hash = Json::hash(['id' => 1, 'status' => 'active']); // deterministic xxh3 hash string // Pretty-print driver Json::driver('pretty')->encode(['key' => 'value']); // "{\n \"key\": \"value\"\n}" // Global helper json()->encode(['foo' => 'bar']); json('pretty')->encode(['foo' => 'bar']); ``` -------------------------------- ### Manage State with Key-Value Storage Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Interact with the state machine for key-value storage operations on an Eloquent model. Ensure the model uses the `HasStateMachine` trait. ```php $order->state()->set('notes', 'Special handling'); $order->state()->get('notes'); $order->state()->has('notes'); $order->state()->forget('notes'); ``` -------------------------------- ### Data DTO Creation and Serialization Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Create lightweight Data Transfer Objects (DTOs) by extending the Data class. Use Data::from() to instantiate from an array and ->toArray() to serialize back. ```php use Utilitarian\Data\Data; class AddressData extends Data { public function __construct( public readonly string $street, public readonly string $city, public readonly string $country, public readonly ?string $postcode = null, ) {} } $address = AddressData::from([ 'street' => '123 Main St', 'city' => 'Springfield', 'country' => 'US', 'postcode' => '62701', ]); echo $address->city; // 'Springfield' echo $address->country; // 'US' $array = $address->toArray(); // ['street' => '123 Main St', 'city' => 'Springfield', 'country' => 'US', 'postcode' => '62701'] ``` -------------------------------- ### Build Cache Keys with CacheUtils Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Use CacheUtils to build cache keys by joining parts with a configurable delimiter. The MakeCacheKey trait provides a convenient makeKey() method for classes. ```php use Utilitarian\Cache\CacheUtils; $utils = new CacheUtils(delimiter: ':'); $utils->buildCacheKey('users', 42, 'profile'); // 'users:42:profile' $utils->buildCacheKey('team', [1, 2], 'stats'); // 'team:1:2:stats' $utils->buildCacheKey(['orders', 'pending'], 'count'); // 'orders:pending:count' ``` ```php class UserRepository { use \Utilitarian\Cache\Concerns\MakeCacheKey; protected string $cachePrefix = 'users'; public function cacheUtils(): CacheUtils { return app(CacheUtils::class); } public function find(int $id): ?User { $key = $this->makeKey($id, 'profile'); // 'users:42:profile' return cache()->remember($key, 3600, fn () => User::find($id)); } } ``` -------------------------------- ### Utility Methods for Enums with EnumHelper Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Use the EnumHelper facade to interact with Backed and Unit enums without modifying enum classes. It provides methods to check for existence, retrieve all values or names, and resolve enum cases from their values. ```php use Utilitarian\Facades\EnumHelper; enum Color: string { case Red = 'red'; case Green = 'green'; case Blue = 'blue'; } enum Direction { case North; case South; case East; case West; } // Check if a value/name exists EnumHelper::exists(Color::class, 'red'); // true EnumHelper::exists(Color::class, 'purple'); // false EnumHelper::exists(Direction::class, 'North'); // true (matches by name) // Get all values / names EnumHelper::values(Color::class); // ['red', 'green', 'blue'] EnumHelper::names(Color::class); // ['Red', 'Green', 'Blue'] EnumHelper::names(Direction::class); // ['North', 'South', 'East', 'West'] // Resolve a case from its value $color = EnumHelper::fromValue(Color::class, 'green'); // Color::Green EnumHelper::fromValue(Color::class, 'nope'); // null // Accept enum instance directly EnumHelper::fromValue(Color::Red, Color::Red); // Color::Red ``` -------------------------------- ### Define and Dispatch a CQRS Action Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Encapsulates business orchestration by coordinating multiple commands and queries. Fires events when EventMiddleware is active. Can be dispatched directly or via ActionBus. ```php use Utilitarian\Cqrs\Action; use Utilitarian\Facades\ActionBus; class RegisterUserAction extends Action { public function __construct( private readonly string $email, private readonly string $name, private readonly string $role = 'user', ) {} public function execute(): User { $user = CreateUserCommand::make( email: $this->email, name: $this->name, role: $this->role, )->dispatch(); SendWelcomeEmailCommand::make(userId: $user->id)->dispatch(); AssignDefaultPermissionsCommand::make(user: $user)->dispatch(); return $user; } } $user = RegisterUserAction::make( email: 'ada@example.com', name: 'Ada Lovelace' )->dispatch(); // Or via bus $user = ActionBus::execute( RegisterUserAction::make(email: 'ada@example.com', name: 'Ada Lovelace') ); ``` -------------------------------- ### Code Quality Checks and Fixes Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Commands to maintain code style consistency. `composer lint` attempts to automatically fix style issues, while `composer lint:test` checks for violations without modifying files. ```bash composer lint # Fix code style composer lint:test # Check code style ``` -------------------------------- ### State Machine FlowHandler with Separate Class Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Keep state machine lifecycle logic in a dedicated class by implementing the FlowHandler interface. Use the useFlow() method to attach the handler to your state machine. ```php use Utilitarian\StateMachine\Contracts\FlowHandler; use Illuminate\Database\Eloquent\Model; use UnitEnum; class OrderFlowHandler implements FlowHandler { public function onEnter(UnitEnum $state, array $data, Model $entity): void { match ($state) { OrderStatus::Paid => SendInvoiceCommand::make(order: $entity)->dispatch(), OrderStatus::Shipped => SendTrackingEmailCommand::make(order: $entity, tracking: $data['tracking_number'] ?? '')->dispatch(), default => null, }; } public function onExit(UnitEnum $state, array $data, Model $entity): void {} } $order->state() ->useFlow(new OrderFlowHandler) ->transitionTo(OrderStatus::Paid); ``` -------------------------------- ### Managing Flash Messages with Alert Facade Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt The Alert facade simplifies handling flash messages in Laravel sessions. You can push messages of different types (success, error, warning, info), check for their presence, retrieve them destructively, or peek at them non-destructively. Duplicate messages are ignored. ```php use Utilitarian\Facades\Alert; // Push alerts Alert::success('Profile updated successfully.'); Alert::error('Payment could not be processed.'); Alert::warning('Your subscription expires in 3 days.'); Alert::info('Maintenance window: Sunday 02:00–04:00 UTC.'); // Check presence Alert::has(AlertType::Success); // true Alert::hasAny(); // true // Read (destructive — removes from session) $successes = Alert::get(AlertType::Success); // [uuid => AlertData(type: Success, message: 'Profile updated successfully.')] // Peek (non-destructive) $errors = Alert::peek(AlertType::Error); // Iterate all (destructive) foreach (Alert::all() as $id => $alertData) { echo "{$alertData->type->value}: {$alertData->message}\n"; } ``` -------------------------------- ### Generate Fast Hashes with fast_hash() Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Utilize the global fast_hash() helper to generate non-cryptographic hashes, suitable for cache keys or ETags. Ensures hash determinism for identical inputs. ```php // Global helper $hash = fast_hash('some string value'); // 'a3f2c...' (xxh3 hex digest) ``` ```php // Use as a cache key component $key = 'query:' . fast_hash(json_encode($queryParams)); cache()->remember($key, 300, fn () => expensiveQuery($queryParams)); ``` ```php // Hash determinism fast_hash('hello') === fast_hash('hello'); // true fast_hash('hello') !== fast_hash('world'); // true ``` -------------------------------- ### Wrap Command Execution in Database Transaction Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Use TransactionMiddleware to automatically wrap command execution in a database transaction. It ensures that all database operations within the command are committed on success or rolled back on any exception. ```php use Utilitarian\Cqrs\Command; use Utilitarian\Cqrs\Middleware\TransactionMiddleware; class TransferFundsCommand extends Command { public function __construct( private readonly int $fromAccountId, private readonly int $toAccountId, private readonly float $amount, ) {} public function middleware(): array { return [TransactionMiddleware::class]; } public function execute(): void { $from = Account::lockForUpdate()->findOrFail($this->fromAccountId); $to = Account::lockForUpdate()->findOrFail($this->toAccountId); if ($from->balance < $this->amount) { throw new \DomainException('Insufficient funds'); } $from->decrement('balance', $this->amount); $to->increment('balance', $this->amount); } } try { TransferFundsCommand::make( fromAccountId: 1, toAccountId: 2, amount: 500.00 )->dispatch(); } catch (\DomainException $e) { // Transaction automatically rolled back logger()->error($e->getMessage()); } ``` -------------------------------- ### Perform Authorization Checks Before Execution Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Utilize AuthorizationMiddleware to enforce authorization checks prior to command execution. It supports custom logic via the authorize() method or policy-based checks using ability() and model(). ```php use Utilitarian\Cqrs\Command; use Utilitarian\Cqrs\Middleware\AuthorizationMiddleware; use Illuminate\Contracts\Auth\Access\Gate; use Illuminate\Auth\Access\AuthorizationException; class DeletePostCommand extends Command { public function __construct( private readonly Post $post ) {} public function middleware(): array { return [AuthorizationMiddleware::class]; } // Pattern 1: custom authorize() public function authorize(Gate $gate): bool { return $gate->allows('delete', $this->post); } public function execute(): void { $this->post->delete(); } } // Pattern 2: ability + model (resolved via PostPolicy) class PublishPostCommand extends Command { public function __construct(private readonly Post $post) {} public function middleware(): array { return [AuthorizationMiddleware::class]; } public function ability(): string { return 'publish'; } public function model(): mixed { return $this->post; } public function execute(): void { $this->post->update(['published' => true]); } } try { DeletePostCommand::make(post: $post)->dispatch(); } catch (AuthorizationException $e) { abort(403, $e->getMessage()); } ``` -------------------------------- ### Caching Query Results with CachingMiddleware Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Caches query results using Laravel's cache. Requires the query to implement 'cacheKey(): string' and optionally 'cacheTtl(): int'. The second call to dispatch() returns the cached value. ```php use Utilitarian\Cqrs\Query; use Utilitarian\Cqrs\Middleware\CachingMiddleware; class GetDashboardStatsQuery extends Query { public function __construct( private readonly int $teamId ) {} public function middleware(): array { return [CachingMiddleware::class]; } public function cacheKey(): string { return "dashboard:stats:{ $this->teamId }"; } public function cacheTtl(): int { return 300; // 5 minutes } public function execute(): array { return [ 'users' => User::where('team_id', $this->teamId)->count(), 'orders' => Order::where('team_id', $this->teamId)->count(), 'revenue' => Order::where('team_id', $this->teamId)->sum('total'), ]; } } $stats = GetDashboardStatsQuery::make(teamId: 7)->dispatch(); // ['users' => 12, 'orders' => 340, 'revenue' => 15200.00] // Second call returns cached value ``` -------------------------------- ### Define Per-Operation Middleware Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Specify custom middleware for a specific operation using `middleware()` and exclude unwanted middleware using `excludeMiddleware()`. Ensure middleware classes are correctly namespaced. ```php class MyQuery extends Query { public function middleware(): array { return [CustomMiddleware::class]; } public function excludeMiddleware(): array { return [UnwantedMiddleware::class]; } } ``` -------------------------------- ### Create Data Object from Array Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Instantiate a Data object from an associative array. This is useful for mapping incoming data, such as from API requests or database results, to structured objects. ```php use Utilitarian\Data\Data; class UserData extends Data { public function __construct( public readonly int $id, public readonly string $email, public readonly string $name, ) {} } // Create from array $userData = UserData::from([ 'id' => 1, 'email' => 'user@example.com', 'name' => 'John Doe', ]); // Convert back to array $array = $userData->toArray(); ``` -------------------------------- ### Add Metadata to Routes with RouteMetadataMacro Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Attach arbitrary metadata to Laravel route definitions using meta() and withMeta() macros. Retrieve metadata using getMeta() and check for its existence with hasMeta(). ```php use Illuminate\Support\Facades\Route; // Single key Route::get('/admin/users', [AdminUserController::class, 'index']) ->meta('permission', 'admin.users.read') ->meta('cache_ttl', 60); ``` ```php // Multiple keys at once Route::post('/orders', [OrderController::class, 'store']) ->withMeta([ 'permission' => 'orders.create', 'rate_limit' => 30, 'audit' => true, ]); ``` ```php // Read in middleware $permission = request()->route()->getMeta('permission'); // 'orders.create' $allMeta = request()->route()->getMeta(); // ['permission' => ..., 'rate_limit' => 30, ...] $hasAudit = request()->route()->hasMeta('audit'); // true $missing = request()->route()->getMeta('non_existent'); // null ``` -------------------------------- ### Run Specific Test Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Execute a single test case or a group of tests by specifying a filter. This is useful for focused debugging or verifying specific functionality. ```bash vendor/bin/pest --filter TestName # Run specific test ``` -------------------------------- ### Implement State Machine Trait Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Use the `HasStateMachine` trait in an Eloquent model to enable state management capabilities. ```php use Utilitarian\StateMachine\Traits\HasStateMachine; class Order extends Model { use HasStateMachine; } ``` -------------------------------- ### Implement Enum States with Transition Rules Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Enforce allowed transitions by implementing `FlowHandler` on the enum. Invalid transitions throw `InvalidTransitionException` and fire a `TransitionFailed` event. The `onEnter` method can execute logic upon entering a state. ```php use Utilitarian\StateMachine\Contracts\FlowHandler; use UnitEnum; enum OrderStatus: string implements FlowHandler { case Pending = 'pending'; case Paid = 'paid'; case Shipped = 'shipped'; case Canceled = 'canceled'; public function canTransitionTo(UnitEnum $target): bool { return match ($this) { self::Pending => in_array($target, [self::Paid, self::Canceled]), self::Paid => $target === self::Shipped, self::Shipped => false, self::Canceled => false, }; } public function onEnter(UnitEnum $state, array $data, \Illuminate\Database\Eloquent\Model $entity): void { if ($state === self::Paid) { SendOrderPaidNotification::dispatch($entity); } } public function onExit(UnitEnum $state, array $data, \Illuminate\Database\Eloquent\Model $entity): void {} } use Utilitarian\StateMachine\Exceptions\InvalidTransitionException; $order->state()->transitionTo(OrderStatus::Paid); // OK: Pending → Paid $order->state()->transitionTo(OrderStatus::Shipped); // OK: Paid → Shipped try { $order->state()->transitionTo(OrderStatus::Paid); // Throws: Shipped → Paid not allowed } catch (InvalidTransitionException $e) { // $e->getMessage() describes the invalid transition } ``` -------------------------------- ### Transition Enum States (with rules) Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Defines an enum with explicit transition rules using the `canTransitionTo` method. Transitions that violate these rules will throw an `InvalidTransitionException`. ```php enum OrderState: string implements FlowHandler { case Pending = 'pending'; case Paid = 'paid'; case Shipped = 'shipped'; public function canTransitionTo(UnitEnum $target): bool { return match ($this) { self::Pending => $target === self::Paid, self::Paid => $target === self::Shipped, self::Shipped => false, }; } } $order->state()->transitionTo(OrderState::Paid); // OK $order->state()->transitionTo(OrderState::Shipped); // throws InvalidTransitionException ``` -------------------------------- ### Validate Operation Before Execution Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Employ ValidationMiddleware to automatically call the validate() method on an operation before its execution. This middleware throws a ValidationException if validation fails, preventing further execution. ```php use Utilitarian\Cqrs\Command; use Utilitarian\Cqrs\Middleware\ValidationMiddleware; use Illuminate\Validation\ValidationException; class UpdateProfileCommand extends Command { public function __construct( private readonly string $email, private readonly string $bio, ) {} public function middleware(): array { return [ValidationMiddleware::class]; } public function validate(): void { if (! filter_var($this->email, FILTER_VALIDATE_EMAIL)) { throw ValidationException::withMessages([ 'email' => ['The email address is invalid.'], ]); } if (strlen($this->bio) > 500) { throw ValidationException::withMessages([ 'bio' => ['Bio must not exceed 500 characters.'], ]); } } public function execute(): void { auth()->user()->update([ 'email' => $this->email, 'bio' => $this->bio, ]); } } try { UpdateProfileCommand::make(email: 'not-an-email', bio: '')->dispatch(); } catch (ValidationException $e) { // $e->errors() => ['email' => ['The email address is invalid.']] } ``` -------------------------------- ### Define a Self-Validating Immutable Value Object Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Extend ValueObject to create immutable objects with built-in validation. Define static $rules and a private constructor. Use make() for instantiation and equals() for comparison. Invalid values will throw an exception. ```php use Utilitarian\ValueObject\ValueObject; class Email extends ValueObject { protected static array $rules = ['email']; protected function __construct(private readonly string $value) {} public function value(): string { return $this->value; } } $email = Email::make('user@example.com'); echo $email->value(); // 'user@example.com' $email->equals(Email::make('user@example.com')); // true $email->equals(Email::make('other@example.com')); // false try { Email::make('not-an-email'); // throws \InvalidArgumentException } catch (\InvalidArgumentException $e) { echo $e->getMessage(); // 'The value must be a valid email address.' } ``` -------------------------------- ### Data DTO Field Renaming with MapField Attribute Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Use the #[MapField('source_key')] attribute to map source array keys to differently named constructor parameters. Supports dot-notation for nested keys and automatic snake_to_camel conversion. ```php use Utilitarian\Data\Data; use Utilitarian\Data\Attributes\MapField; use Utilitarian\Data\Mapping\Field\SnakeToCamel; class UserData extends Data { public function __construct( public readonly int $id, // maps 'email_address' in source → $email parameter #[MapField('email_address')] public readonly string $email, // auto snake_to_camel conversion: 'first_name' → $firstName #[MapField(SnakeToCamel::class)] public readonly string $firstName, ) {} } $user = UserData::from([ 'id' => 42, 'email_address' => 'john@example.com', 'first_name' => 'John', ]); echo $user->email; // 'john@example.com' echo $user->firstName; // 'John' ``` -------------------------------- ### Custom Field Mapping in Data Object Source: https://github.com/utilitarian-dev/utilitarian-laravel-toolkit/blob/main/README.md Define custom mapping between array keys and object properties using the `#[MapField]` attribute. This allows for flexible data input when array keys do not directly match property names. ```php use Utilitarian\Data\Attributes\MapField; class UserData extends Data { public function __construct( public readonly int $id, #[MapField('email_address')] public readonly string $email, ) {} } ``` -------------------------------- ### Extract Multiple Values with array_get_many() Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Use the array_get_many() helper to extract multiple values from an array using named keys or positional fallbacks. Useful for unpacking arrays with mixed data types or structures. ```php $data = ['user_id' => 42, 'role' => 'editor', 'active' => true]; $extracted = array_get_many($data, ['user_id', 'role']); // ['user_id' => 42, 'role' => 'editor'] ``` ```php // Positional fallback: if 'name' key absent, falls back to position 0 $positional = array_get_many([0 => 'Alice', 1 => 'admin'], ['name', 'role']); // ['name' => 'Alice', 'role' => 'admin'] ``` -------------------------------- ### Data DTO Type Casting with MapTransform Attribute Source: https://context7.com/utilitarian-dev/utilitarian-laravel-toolkit/llms.txt Apply type casting to raw values using the #[MapTransform(TransformClass::class)] attribute. Supports built-in transforms like EnumTransform, ModelTransform, and CollectionTransform. ```php use Utilitarian\Data\Data; use Utilitarian\Data\Attributes\MapField; use Utilitarian\Data\Attributes\MapTransform; use Utilitarian\Data\Mapping\Transform\EnumTransform; use Utilitarian\Data\Mapping\Transform\ModelTransform; use Utilitarian\Data\Mapping\Transform\CollectionTransform; class OrderData extends Data { public function __construct( public readonly int $id, // 'status' string → OrderStatus enum via tryFrom() #[MapTransform(EnumTransform::class)] public readonly OrderStatus $status, // 'customer_id' integer → Customer model via ::find() #[MapField('customer_id')] #[MapTransform(ModelTransform::class)] public readonly Customer $customer, // 'tags' array → Illuminate\Support\Collection #[MapTransform(CollectionTransform::class)] public readonly \Illuminate\Support\Collection $tags, ) {} } $order = OrderData::from([ 'id' => 1, 'status' => 'paid', 'customer_id' => 7, 'tags' => ['urgent', 'wholesale'], ]); echo $order->status->value; // 'paid' echo $order->customer->name; // 'Acme Corp' (loaded from DB) $order->tags->contains('urgent'); // true ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.