feat: `histories` table

This commit is contained in:
b1ek 2024-08-30 07:50:29 +10:00
parent 1e27b8447a
commit 0ca5a445f5
Signed by: blek
GPG Key ID: 14546221E3595D0C
6 changed files with 125 additions and 2 deletions

11
app/HasHistory.php Normal file
View File

@ -0,0 +1,11 @@
<?php
namespace App;
trait HasHistory
{
public static function bootHasHistory()
{
static::observe(HistoryObserver::class);
}
}

10
app/HistoryAction.php Normal file
View File

@ -0,0 +1,10 @@
<?php
namespace App;
enum HistoryAction: string
{
case Insert = 'insert';
case Update = 'update';
case Delete = 'delete';
}

40
app/HistoryObserver.php Normal file
View File

@ -0,0 +1,40 @@
<?php
namespace App;
use App\Models\History;
class HistoryObserver
{
public function created($model)
{
History::create([
'model_id' => $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,
]);
}
}

30
app/Models/History.php Normal file
View File

@ -0,0 +1,30 @@
<?php
namespace App\Models;
use App\HistoryAction;
use App\UuidId;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class History extends Model
{
use HasFactory, UuidId;
protected $fillable = [
'model_id',
'model_name',
'before',
'after',
'action',
];
protected function casts()
{
return [
'action' => HistoryAction::class,
'before' => 'array',
'after' => 'array',
];
}
}

View File

@ -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.

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('histories', function (Blueprint $table) {
$table->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');
}
};