定制 xcopy/laravel-model-state-transitions 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

xcopy/laravel-model-state-transitions

Composer 安装命令:

composer require xcopy/laravel-model-state-transitions

包简介

Manage state transitions for your Laravel models with role-based access control and automatic history tracking.

README 文档

README

GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Manage state transitions for your Laravel models with role-based access control and automatic history tracking.

Features

  • Define valid state transitions for any Eloquent model
  • Role-based access control (RBAC) for transitions - users and roles can be authorized
  • Automatic transition history tracking with complete audit trail and user attribution
  • Type-safe enum support – automatic casting between database values and BackedEnum instances
  • Polymorphic relationships for flexible model support
  • Custom properties and descriptions for each transition with metadata support
  • Query available transitions based on current state and user permissions
  • Convenience methods for state transitions with metadata (stateTransitionTo(), setTransitionMetadata())
  • Automatic user tracking via EloquentBlameable integration

Installation

Note: This package is not yet available on Packagist. You must add it to your composer.json manually.

composer require xcopy/laravel-model-state-transitions:dev-main

Run the installation commands:

php artisan vendor:publish --provider="Jenishev\Laravel\ModelStateTransitions\ModelStateTransitionsServiceProvider" --tag=config
php artisan vendor:publish --provider="Jenishev\Laravel\ModelStateTransitions\ModelStateTransitionsServiceProvider" --tag=migrations
php artisan migrate

Quick Start

1. Create a State Enum

namespace App\Enums;

enum PaymentStateEnum: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    // ...
}

2. Add Trait to Your Model

use Jenishev\Laravel\ModelStateTransitions\Concerns\HasStateTransitions as HasStateTransitionsConcern;
use Jenishev\Laravel\ModelStateTransitions\Contracts\HasStateTransitions as HasStateTransitionsContract;

class Payment extends Model implements HasStateTransitionsContract
{
    use HasStateTransitionsConcern;

    protected $fillable = [
        // ...
        'state'
    ];

    protected function casts(): array
    {
        return [
            'state' => PaymentStateEnum::class,
            // ... other casts
        ];
    }

    // Override only if using custom enum naming convention,
    // By default, expects: App\Enums\{ModelName}StateEnum
    public static function resolveStateEnum(): string
    {
        return PaymentStateEnum::class;
    }
}

3. Define Transitions

use Jenishev\Laravel\ModelStateTransitions\Models\Transition;

// Create a transition definition
$transition = Transition::create([
    'model_type' => Payment::class,
    'from_state' => PaymentStateEnum::Pending,
    'to_state' => PaymentStateEnum::Paid,
]);

// Authorize specific users
$transition->users()->attach($userId);

// Authorize by role
$transition->roles()->attach($roleId);

// Or authorize multiple at once
$transition->users()->attach([$userId1, $userId2]);
$transition->roles()->attach([$adminRoleId, $managerRoleId]);

4. Use in Your Application

// Check available transitions for current user
$availableTransitions = $payment->transitions()->get();

// Perform transition with metadata
$payment->stateTransitionTo(
    state: PaymentStateEnum::Paid,
    description: 'Payment confirmed'
);

// View history
foreach ($payment->transitionHistory as $history) {
    echo "{$history->from_state->value}{$history->to_state->value} by user {$history->creator->name}";
    // OR
    // echo "{$history->from_state->label()} → {$history->to_state->label()}";
}

Usage

Performing State Transitions

The package provides multiple ways to transition between states:

Simple State Change (Auto-tracked)

// Direct state change - automatically tracked in history
$payment->state = PaymentStateEnum::Paid;
$payment->save();

Transition with Metadata (Recommended)

// Use stateTransitionTo() for convenience - transitions and saves in one call
$payment->stateTransitionTo(
    state: PaymentStateEnum::Paid,
    description: 'Payment approved by manager',
    custom_properties: [
        'approved_by' => $manager->id,
        'approval_method' => 'manual',
        'notes' => 'All documents verified'
    ]
);

Set Metadata Before Saving

// Set metadata first, then update the state
$payment->setTransitionMetadata(
    description: 'Payment rejected due to insufficient funds',
    custom_properties: ['reason_code' => 'INSUFFICIENT_FUNDS']
);
$payment->state = PaymentStateEnum::Rejected;
$payment->save();

Get Available Transitions

// For authenticated user
$payment->transitions()->get();

// For specific user
$payment->transitions($user)->get();

// Check if a specific transition exists
$payment->transitions()
    ->where('to_state', PaymentStateEnum::Paid)
    ->exists();

Query History

// Get all transitions for a model
$payment->transitionHistory;

// Latest transition
$payment->transitionHistory()->latest()->first();

// Filter by state
$payment->transitionHistory()
    ->where('to_state', PaymentStateEnum::Paid)
    ->get();

// Access enum values
$history = $payment->transitionHistory()->latest()->first();
$history->from_state; // Returns PaymentStateEnum::Pending
$history->to_state;   // Returns PaymentStateEnum::Paid

// Access metadata
$history->description;
$history->custom_properties; // Array of custom data
$history->created_by; // User ID who made the transition

Advanced Usage

Attaching Transitions to Users/Roles

To query available transitions from the user or role side, add the HasAttachedTransitions trait:

use Jenishev\Laravel\ModelStateTransitions\Concerns\HasAttachedTransitions;

class User extends Authenticatable
{
    use HasAttachedTransitions;
    
    // ... existing code
}

class Role extends Model
{
    use HasAttachedTransitions;
    
    // ... existing code
}

This enables:

// Get all transitions available to a user
$user->transitions;

// Attach a transition to a user
$user->transitions()->attach($transitionId);

// Check if a user has a specific transition
$user->transitions()->where('to_state', 'approved')->exists();

Configuration

The package provides sensible defaults out of the box. You can customize the behavior by editing the published configuration file at config/model-state-transitions.php.

Key configuration options include:

  • transitions_table - Table storing state transition definitions (default: transitions)
  • transition_history_table - Audit trail table (default: transition_history)
  • pivot_table - User/Role authorization pivot table (default: model_has_transitions)
  • transitionable_state_column - Column name on your models (default: state)
  • transition_model - Transition model class (customizable)
  • transition_history_model - History model class (customizable)
  • role_model - Your application's Role model (customizable)
  • user_model - Your application's User model (customizable)

Refer to the config file for detailed documentation on each option.

Testing

composer test
composer format
composer analyse

Changelog

Please see CHANGELOG for more information on what has changed recently.

License

The MIT License (MIT). Please see License File for more information.

xcopy/laravel-model-state-transitions 适用场景与选型建议

xcopy/laravel-model-state-transitions 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「state」 「laravel」 「transition」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 xcopy/laravel-model-state-transitions 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 xcopy/laravel-model-state-transitions 我们能提供哪些服务?
定制开发 / 二次开发

基于 xcopy/laravel-model-state-transitions 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 4
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 39
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-22