+1 (415) 599-8902

Building an Audit Trail in Laravel: Eloquent Events, Activity Logs and Tamper-Resistant History

Sooner or later a customer asks, "who changed this invoice, and when?" Enterprise buyers and auditors ask it constantly. This tutorial builds an audit trail in Laravel that answers it: what to record, how to capture it with Eloquent events, how to keep it from slowing requests, and how to keep sensitive data out of it.

You need a Laravel 11+ app and a database. Package names below are real; check each package's docs for the version matching your Laravel release.

Decide what an audit record contains

A useful entry has: the actor (user or system), the action, the subject (model type and ID), the old and new values, a timestamp, and request context (IP, request ID). Write this down first. It is much harder to add later.

Option 1: A hand-rolled observer

For one or two models, an observer is enough.

php artisan make:model AuditEntry -m
php artisan make:observer InvoiceObserver --model=Invoice
Schema::create('audit_entries', function (Blueprint $table) {
    $table->id();
    $table->nullableMorphs('actor');
    $table->morphs('subject');
    $table->string('event');
    $table->json('old_values')->nullable();
    $table->json('new_values')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->timestamp('created_at')->useCurrent();
    $table->index(['subject_type', 'subject_id', 'created_at']);
});
class InvoiceObserver
{
    public function updated(Invoice $invoice): void
    {
        $changes = $invoice->getChanges();
        unset($changes['updated_at']);

        if ($changes === []) {
            return;
        }

        AuditEntry::create([
            'actor_type' => auth()->user()?->getMorphClass(),
            'actor_id' => auth()->id(),
            'subject_type' => $invoice->getMorphClass(),
            'subject_id' => $invoice->getKey(),
            'event' => 'updated',
            'old_values' => array_intersect_key($invoice->getOriginal(), $changes),
            'new_values' => $changes,
            'ip_address' => request()->ip(),
        ]);
    }
}

Register it with the #[ObservedBy(InvoiceObserver::class)] attribute on the model. Note that getOriginal() and getChanges() are only reliable inside updated, after the save.

Option 2: spatie/laravel-activitylog

For many models, use the package instead of repeating yourself.

composer require spatie/laravel-activitylog

Then publish and run its migrations as described in its docs. Configure each model:

use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Invoice extends Model
{
    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['status', 'total', 'due_date'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}

logOnly is an allow-list, which is safer than logging everything. logOnlyDirty stores only the fields that changed.

Know the blind spots

Eloquent events fire only when you go through models. These bypass them:

  • Invoice::where(...)->update([...]) and mass delete() queries
  • DB::table(...) calls and raw SQL
  • insert() and upsert()

In audited code paths, iterate models (->each->update()), or use chunkById so events fire, or write an explicit audit entry for bulk operations. Add a code review rule for this.

Redact sensitive fields

Never log passwords, tokens, card data, or full personal data. Prefer allow-lists over logExcept. If you must record that a sensitive field changed, store a marker instead of the value:

'new_values' => ['api_token' => '[changed]'],

Also remember that audit tables fall under privacy rules: plan how to handle erasure requests, for example by anonymising the actor reference rather than deleting history.

Keep writes off the hot path

An extra insert per save is cheap, but a busy system adds up. Dispatch the write to a queue, passing plain arrays rather than models:

WriteAuditEntry::dispatch($payload)->onQueue('audit');

Capture the actor and IP before dispatching, because a queue worker has no request. Accept the trade-off: a queued write can be lost if the job fails permanently, so monitor failed jobs on the audit queue. For compliance-critical events, write synchronously inside the same database transaction as the change, so both succeed or neither does.

Make the history hard to tamper with

  • Grant the application's database user INSERT and SELECT only on the audit table, with no UPDATE or DELETE. Run pruning with a separate privileged role.
  • Expose no edit or delete endpoints.
  • For stronger guarantees, ship entries to append-only storage or a log service as well.

Retention

Keep audit data for as long as policy requires and no longer. With the activitylog package, schedule its clean command; with a custom table, use the Prunable trait:

use Illuminate\Database\Eloquent\Prunable;

public function prunable(): Builder
{
    return static::where('created_at', '<', now()->subYears(2));
}

Then schedule model:prune daily.

Test it

it('records who changed an invoice', function () {
    $user = User::factory()->create();
    $invoice = Invoice::factory()->create(['status' => 'draft']);

    $this->actingAs($user);
    $invoice->update(['status' => 'paid']);

    $entry = AuditEntry::latest('id')->first();
    expect($entry->actor_id)->toBe($user->id)
        ->and($entry->old_values)->toBe(['status' => 'draft'])
        ->and($entry->new_values)->toBe(['status' => 'paid']);
});

Add a test that a sensitive field never appears in new_values, and one that a no-op save writes nothing.

Checklist

  • Define the record shape before coding.
  • Allow-list audited fields.
  • Cover bulk and raw-query paths deliberately.
  • Capture actor and request context before queueing.
  • Restrict database permissions on the audit table.
  • Schedule retention and pruning.

If you are adding auditability to an existing Laravel application, or need to meet a compliance requirement, our team can help with design and implementation.