Building a Polymorphic Audit Trail for Eloquent Models
"Who changed this invoice's total, and when?" is one of those questions that's easy to ignore until a customer disputes a charge and you have nothing to show them. This tutorial builds a reusable audit trail — one table, one trait, applied to any model — that records every create, update, and delete with a diff of what changed.
Step 1: The migration
One table handles every auditable model, thanks to a polymorphic relationship:
Schema::create('activity_logs', function (Blueprint $table) {
$table->id();
$table->morphs('subject');
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
$table->string('event');
$table->json('changes')->nullable();
$table->timestamps();
});
morphs('subject') gives you subject_type and subject_id, so the same table can log activity on Invoice, Order, User, or anything else without a table per model.
Step 2: The ActivityLog model
class ActivityLog extends Model
{
protected $guarded = [];
protected $casts = [
'changes' => 'array',
];
public function subject(): MorphTo
{
return $this->morphTo();
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
Step 3: A reusable Auditable trait
This is where the real work happens — hooking into Eloquent's model events to capture a diff automatically:
trait Auditable
{
public static function bootAuditable(): void
{
static::created(fn ($model) => $model->recordActivity('created', $model->getAttributes()));
static::updated(function ($model) {
if ($model->wasChanged()) {
$model->recordActivity('updated', $model->getChanges());
}
});
static::deleted(fn ($model) => $model->recordActivity('deleted', null));
}
public function recordActivity(string $event, ?array $changes): void
{
$this->activityLogs()->create([
'user_id' => auth()->id(),
'event' => $event,
'changes' => $changes,
]);
}
public function activityLogs(): MorphMany
{
return $this->morphMany(ActivityLog::class, 'subject');
}
}
wasChanged() guards against logging a no-op save (calling save() on a model with no dirty attributes shouldn't produce a log entry).
Step 4: Apply it to a model
class Invoice extends Model
{
use Auditable;
// ...
}
That's it. Every create, meaningful update, and delete against Invoice now writes a row to activity_logs automatically, with the acting user's ID and a JSON diff of exactly what changed.
Step 5: Displaying the trail
$invoice->activityLogs()
->with('user')
->latest()
->get()
->each(function ($log) {
echo "{$log->user?->name} {$log->event} at {$log->created_at}: " . json_encode($log->changes);
});
Handling attribute exclusions
You almost never want to log every column — timestamps and internal flags create noise. Add an $auditExclude property to models and filter it in recordActivity():
public function recordActivity(string $event, ?array $changes): void
{
if ($changes) {
$changes = collect($changes)
->except($this->auditExclude ?? ['updated_at'])
->all();
if (empty($changes)) {
return;
}
}
$this->activityLogs()->create([
'user_id' => auth()->id(),
'event' => $event,
'changes' => $changes,
]);
}
A note on scale
For a handful of auditable models this table stays small and fast with a composite index on subject_type/subject_id (which morphs() already creates). If you're logging high-frequency changes across dozens of models, consider queuing the write with ShouldQueue on a listener instead of writing inline during the request, and set a retention policy — a scheduled command that prunes logs older than your compliance window is usually enough to keep the table from growing unbounded.