我有一个名为 RecordsUserActivity 的特征,它基本上在用户创建、更新或删除使用此特征的内容时在活动表中创建一条记录。这是代码:
trait RecordsUserActivity
{
protected static function boot()
{
parent::boot();
foreach (static::getModelEvents() as $event) {
static::$event(function ($model) use ($event) {
$model->addActivity($event);
});
}
}
protected function addActivity($event)
{
$newActivity = [
'subject_id' => $this->id,
'subject_type' => get_class($this),
'action' => $event,
'user_id' => (Auth::id()) ?? null,
];
if ($event == 'updated') {
$newActivity['data'] = json_encode($this->getDirty());
}
UserActivity::create($newActivity);
}
protected static function getModelEvents()
{
if (isset(static::$recordEvents)) {
return static::$recordEvents;
}
return ['created', 'deleted', 'updated'];
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有另一个特征,它记录使用它的模型中的属性更改。这是代码:
trait RecordsPropertyChangelog
{ …Run Code Online (Sandbox Code Playgroud)