feat: add Company model and TrackedModel trait; update Park model to use Company as owner

This commit is contained in:
pacnpal
2025-02-26 12:58:46 -05:00
parent f6d0ecd82e
commit bcfab9fb74
3 changed files with 80 additions and 2 deletions

View 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(),
]);
}
}