mirror of
https://github.com/pacnpal/thrillwiki_laravel.git
synced 2025-12-20 04:31:10 -05:00
42 lines
1.2 KiB
PHP
42 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
trait TrackedModel {
|
|
protected static function bootTrackedModel() {
|
|
static::created(function (Model $model) {
|
|
static::logChange($model, 'created');
|
|
});
|
|
|
|
static::updated(function (Model $model) {
|
|
static::logChange($model, 'updated');
|
|
});
|
|
|
|
static::deleted(function (Model $model) {
|
|
static::logChange($model, 'deleted');
|
|
});
|
|
}
|
|
|
|
protected static function logChange(Model $model, string $action) {
|
|
$changes = $action === 'updated'
|
|
? [
|
|
'old' => $model->getOriginal(),
|
|
'new' => $model->getDirty()
|
|
]
|
|
: $model->getAttributes();
|
|
|
|
DB::table('model_history')->insert([
|
|
'model_type' => get_class($model),
|
|
'model_id' => $model->getKey(),
|
|
'user_id' => Auth::check() ? Auth::id() : null,
|
|
'action' => $action,
|
|
'changes' => json_encode($changes),
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
}
|
|
} |