如何使用 laravel 5.1 更新记录的 user_id 填充 modified_by?

How to populate the modified_by with the user_id of who made the update to the record using laravel 5.1?

使用 Laravel 5.1 时,我正在尝试创建一个会自动更新以下 3 列的观察器

  1. created_by:在创建记录时填充"never update this again"
  2. modified_by:每修改一条记录填充一个新值
  3. purged_by: 软删除记录时填充一个值。

我知道 Eloquent 会自动更新日期时间戳(created_by、updated_at、removed_at)但我需要更新 user_id做出了改变。

有人建议我使用 Observer 和 trait 来处理这个问题。这是我所做的

1) 在 app\Observers\ModelSignature.php 创建了一个名为 "ModelSignature" 的观察者 class,这就是它的内容

<?php 

namespace App\Observers;

class ModelSignature {

    protected $userID;

    public function __construct(){
        $this->userID =  Auth::id();
    }


    public function updating($model)
    {
        $model->modified_by = $this->userID;
    }


    public function creating($model)
    {
        $model->created_by = $this->userID;
    }


    public function removing($model)
    {
        $model->purged_by = $this->userID;
    }

}

然后我创建了一个名为 "RecordSignature" 的新特征,位于 app\Traits\RecordSignature.php 并包含以下代码

<?php

namespace App\Traits;

use app\Observers\ModelSignature;

trait RecordSignature
{

    public static function bootObservantTrait()
    {
        static::observe(new ModelSignature() );
    }
}

最后,在我位于 "app\Models\Account.php" 的 "Account" 模型中,我这样使用它

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\industry;
use App\Traits\RecordSignature;
use App\Traits\TrimScalarValues;


class Account extends Model
{
    use RecordSignature, TrimScalarValues;
    /**
     * The database table used by the model.
     *
     * @var string
    */
    protected $table = 'accounts';

    protected $primaryKey = 'account_id';

    const CREATED_AT = 'created_on';

    const UPDATED_AT = 'modified_on';

    const REMOVED_AT = 'purged_on';


    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    protected $fillable = ['client_id','account_name', 'company_code', 'legal_name', 'created_by','modified_by','instrucations'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
    */
    //protected $hidden = ['account_id', 'remember_token'];


    protected $guarded = ['account_id'];

    /**
     * Get the industry record associated with the account.
    */
    public function industry()
    {
        return $this->hasOne(industry, industry::primaryKey);
    }

    public function pk(){

        return $this->primaryKey;
    }

}

问题是方法 updating()removing()creating() 没有按预期填充 userId。似乎字段被忽略或方法没有被触发!

我做错了什么?

您应该能够摆脱您的 ModelSignatures Class 并将您的特征更改为:

trait RecordSignature
{
    protected static function boot()
    {
        parent::boot();

        static::updating(function ($model) {

            $model->modified_by = \Auth::User()->id;
        });

        static::creating(function ($model) {

            $model->created_by = \Auth::User()->id;
        });
        //etc

    }

}

更新:

现在有很多软件包可以为您处理这类事情。我目前经常使用的一个是 Laravel Auditing,它不仅会跟踪谁执行了任务,还会跟踪对行的任何更改。

我建议您在这次升级中使用 venturecraft 可修订包 https://github.com/fico7489/laravel-revisionable-upgrade

一切都开箱即用,您只需要使用 2 个特征,您可以做更多的事情来获取编辑模型的信息,您可以获得编辑特定列的信息,甚至是特定值等等。 .

第 1 步:制作特征

namespace App\Traits;

use App\Observer\ModelObserver;

trait ObservantTrait
{

    public static function bootObservantTrait()
    {
        static::observe(ModelObserver::class);
    }

}

第 2 步:创建观察者

<?php

namespace App\Observer;

use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\Config\Repository;
use Request;

class ModelObserver
{

    public $userID;
    protected $auth;
    protected $login_user;
    protected $ip;
    protected $user_agent;

    public function __construct(AuthManager $auth, Repository $config)
    {
        $this->auth = $auth;
        $this->login_user = $auth->guard($this->auth->getDefaultDriver())->user();
        if (isset($this->login_user->id)) {
            $this->userID = $this->login_user->id;
            $this->ip = Request::ip();
            $this->user_agent = Request::header('user-agent');
        }
    }


    public function updating($model)
    {

        $model->updated_by = $this->userID;
        $model->ip = Request::ip();
        $model->user_agent = Request::header('user-agent');

    }

    public function creating($model)
    {

        $model->created_by = $this->userID;
        $model->ip = Request::ip();
        $model->user_agent = Request::header('user-agent');

    }

    public function deleted($model)
    {

        $model->deleted_by = $this->userID;
        $model->ip = Request::ip();
        $model->user_agent = Request::header('user-agent');
        $model->save();

    }

}

第 3 步:模型中的用户特征

use ObservantTrait;