mirror of
https://github.com/pacnpal/thrillwiki_laravel.git
synced 2025-12-20 09:51:10 -05:00
feat: add Company model and TrackedModel trait; update Park model to use Company as owner
This commit is contained in:
42
app/Traits/TrackedModel.php
Normal file
42
app/Traits/TrackedModel.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user