From 0ca5a445f5bd06b9a27f1ce26554b815a53d08f1 Mon Sep 17 00:00:00 2001 From: b1ek Date: Fri, 30 Aug 2024 07:50:29 +1000 Subject: [PATCH] feat: `histories` table --- app/HasHistory.php | 11 +++++ app/HistoryAction.php | 10 +++++ app/HistoryObserver.php | 40 +++++++++++++++++++ app/Models/History.php | 30 ++++++++++++++ app/Models/User.php | 4 +- ...24_08_29_211556_create_histories_table.php | 32 +++++++++++++++ 6 files changed, 125 insertions(+), 2 deletions(-) create mode 100644 app/HasHistory.php create mode 100644 app/HistoryAction.php create mode 100644 app/HistoryObserver.php create mode 100644 app/Models/History.php create mode 100644 database/migrations/2024_08_29_211556_create_histories_table.php diff --git a/app/HasHistory.php b/app/HasHistory.php new file mode 100644 index 0000000..76f5a74 --- /dev/null +++ b/app/HasHistory.php @@ -0,0 +1,11 @@ + $model->id, + 'model_name' => $model->getTable(), + 'before' => null, + 'after' => $model->toArray(), + 'action' => HistoryAction::Insert, + ]); + } + + public function updating($model) + { + History::create([ + 'model_id' => $model->id, + 'model_name' => $model->getTable(), + 'before' => $model->getRawOriginal(), + 'after' => $model->getAttributes(), + 'action' => HistoryAction::Update, + ]); + } + + public function deleting($model) + { + History::create([ + 'model_id' => $model->id, + 'model_name' => $model->getTable(), + 'before' => $model->getRawOriginal(), + 'after' => null, + 'action' => HistoryAction::Delete, + ]); + } +} diff --git a/app/Models/History.php b/app/Models/History.php new file mode 100644 index 0000000..d7039d0 --- /dev/null +++ b/app/Models/History.php @@ -0,0 +1,30 @@ + HistoryAction::class, + 'before' => 'array', + 'after' => 'array', + ]; + } +} diff --git a/app/Models/User.php b/app/Models/User.php index c0eb53e..a34c867 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -3,15 +3,15 @@ namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; +use App\HasHistory; use App\UuidId; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; -use Infocyph\UID\UUID; class User extends Authenticatable { - use HasFactory, Notifiable, UuidId; + use HasFactory, Notifiable, UuidId, HasHistory; /** * The attributes that are mass assignable. diff --git a/database/migrations/2024_08_29_211556_create_histories_table.php b/database/migrations/2024_08_29_211556_create_histories_table.php new file mode 100644 index 0000000..3d31871 --- /dev/null +++ b/database/migrations/2024_08_29_211556_create_histories_table.php @@ -0,0 +1,32 @@ +uuid('id'); + $table->uuid('model_id'); + $table->string('model_name', 250); + $table->jsonb('before'); + $table->jsonb('after'); + $table->enum('action', [ 'insert', 'update', 'delete' ]); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('histories'); + } +};