adamcmoore/laravel-approvable

需要批准对Eloquent模型更改

v2.1 2023-11-20 13:03 UTC

README

一个需要批准对Eloquent模型更改的包。

支持Laravel版本10。

设置

要求包

composer require adamcmoore/laravel-approvable

发布并运行迁移

php artisan vendor:publish --provider "AcMoore\Approvable\ApprovableServiceProvider" --tag="migrations" php artisan migrate

设置需要批准的模型

use AcMoore\Approvable\Approvable;
use AcMoore\Approvable\ApprovableContract;

class Article extends Model implements ApprovableContract
{
    use Approvable;
    
    // Only fields set as approvable will be used when considering 
    // if a new version is required, and only these fields will be 
    // stored in the new version. If this isn't set, the $fillable 
    // fields are used.
    public $approvable = [
        'title', 
        'content',
    ];
    
    
    // Optionally set a datetime field on the model to be set with 
    // the date that the draft was first approved. 
    protected $timestamp_field_for_first_approved = 'approved_at';

} 

设置需要批准的相关模型

use AcMoore\Approvable\Approvable;
use AcMoore\Approvable\ApprovableContract;

class ArticleImage extends Model implements ApprovableContract
{
    use Approvable;
    
    public $approvable = [
        'file_url', 
    ];
    
    // Set the name of the parent relation.
    // Currently only belongsTo has been tested
    public $approvable_parent = 'article';
    
    public function article()
    {
        return $this->belongsTo(Article::class);
    }
}

使用示例

$article = Article::find(1)->get();
$article->title = 'New Title';

Article::enableApproval(); 
$article->save();
Article::disableApproval();

...

$article = $article->has('draft')->with('versions')->first();

// The version with a status of draft, rejected, or approved
$draft = $article->draft;

// An Article model with the draft values filled
$preview = $article->draft->preview;

// Set status of version as approved. Version remains as a draft.
$draft->approve('Optional note regarding decision to approve');

// Set status of version as rejected. Version is removed as a draft.
$draft->reject('Optional note regarding decision to reject');

// Write the draft to the database object
$draft->apply('Optional note regarding decision to apply');

// Ignore the draft
$draft->drop('Optional note regarding decision to drop');

更新时强制创建草稿

创建和删除将在启用批准时始终创建草稿。

更新仅在模型属性已更改时才会创建草稿。

要始终创建草稿,即使没有数据已更改,请在Model::enableApproval()之后使用Model::forceDraft();

Eloquent模型事件

当草稿状态改变时,在Approvable模型上触发模型事件。这些可以通过观察者来监听。触发的事件包括

  • new_draft
  • approved
  • rejected
  • dropped
  • applied

待办事项

  • 添加对创建和删除非关系记录的支持
  • 测试和支持其他类型的关联,除了belongsTo