DEV Community

Tuğrul Yıldırım
Tuğrul Yıldırım

Posted on

An Audit Trail for Laravel ERP Apps: Who Changed What, When and Why

A customer calls finance: "Why did this order go out at last month's price?" Finance asks sales. Sales asks the warehouse. Someone opens the database, sees unit_price = 12.50, and that is where the trail ends. The row tells you what the price is. It does not tell you who changed it, when, from what, or why.

In business software that last question matters more than people expect. Prices, credit limits, stock adjustments, approval thresholds and customer payment terms all change for legitimate reasons, and a few times a year they change for wrong ones. When that happens, "we don't know" is an expensive answer.

This post walks through a small, boring and reliable audit trail for Laravel ERP and CRM apps: one table, one trait, a way to attach a business reason, and the pitfalls that quietly make audit logs lie.

The problem with "we have updated_at"

Most apps already have created_at and updated_at. That gives you a timestamp of the last change, with no actor, no previous value, and no history. Teams usually discover this gap during an incident, then bolt on ad-hoc logging inside a few controllers. That fails in predictable ways:

  • The same record is changed from a form, an import command and an API endpoint, but only the form logs anything.
  • The log stores a sentence like "price updated" without the old and new values.
  • Nobody records why, so the log answers "who" and still leaves the real question open.

What we want instead:

  1. Every create, update and delete on selected models produces an audit row automatically.
  2. Each row stores the old and new values of only the fields that changed.
  3. Each row knows the actor: a logged-in user, or a named system process.
  4. Optionally, each row carries a business reason and a trace ID that links it to the request or job that caused it.

Step 1: One table for every audited model

A polymorphic table keeps things simple. One audit_logs table can serve products, customers, price lists and purchase orders.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('audit_logs', function (Blueprint $table) {
            $table->id();
            $table->morphs('auditable');          // auditable_type + auditable_id (indexed)
            $table->string('event', 20);          // created | updated | deleted
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->string('actor', 100)->nullable(); // e.g. "system:price-import"
            $table->json('old_values')->nullable();
            $table->json('new_values')->nullable();
            $table->string('reason')->nullable();
            $table->string('trace_id', 64)->nullable()->index();
            $table->timestamp('created_at')->useCurrent();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('audit_logs');
    }
};
Enter fullscreen mode Exit fullscreen mode

A few deliberate choices here:

  • There is no updated_at. Audit rows are append-only; if you ever need to edit one, something is wrong.
  • user_id is nullable with nullOnDelete(), because deleting a user account should not delete the history of what they did.
  • actor covers changes with no logged-in user, such as imports, scheduled jobs and queue workers.

The model is small:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class AuditLog extends Model
{
    public const UPDATED_AT = null; // audit rows are never updated

    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'old_values' => 'array',
            'new_values' => 'array',
        ];
    }

    public function auditable(): MorphTo
    {
        return $this->morphTo();
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: A trait that hooks into Eloquent events

Eloquent dispatches lifecycle events such as created, updated and deleted. A trait with a boot{TraitName} method can register listeners for every model that uses it, so no controller needs to remember to log anything.

<?php

namespace App\Models\Concerns;

use App\Models\AuditLog;
use App\Support\AuditReason;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Context;

trait Auditable
{
    public static function bootAuditable(): void
    {
        static::created(function (Model $model) {
            $model->writeAudit('created', [], $model->auditFilter($model->getAttributes()));
        });

        static::updated(function (Model $model) {
            $new = $model->auditFilter($model->getChanges());

            if ($new === []) {
                return; // only noise changed (e.g. updated_at)
            }

            $old = Arr::only($model->getPrevious(), array_keys($new));

            $model->writeAudit('updated', $old, $new);
        });

        static::deleted(function (Model $model) {
            $model->writeAudit('deleted', $model->auditFilter($model->getAttributes()), []);
        });
    }

    public function auditLogs(): MorphMany
    {
        return $this->morphMany(AuditLog::class, 'auditable')->latest('id');
    }

    /**
     * Attributes that should never be written to the audit trail.
     */
    protected function auditExclude(): array
    {
        $extra = property_exists($this, 'auditExcept') ? $this->auditExcept : [];

        return ['created_at', 'updated_at', 'remember_token', 'password', ...$extra];
    }

    protected function auditFilter(array $attributes): array
    {
        return Arr::except($attributes, $this->auditExclude());
    }

    protected function writeAudit(string $event, array $old, array $new): void
    {
        $this->auditLogs()->create([
            'event'      => $event,
            'user_id'    => Auth::id(),
            'actor'      => Auth::check() ? null : (Context::get('actor') ?? 'system'),
            'old_values' => $old ?: null,
            'new_values' => $new ?: null,
            'reason'     => AuditReason::current(),
            'trace_id'   => Context::get('trace_id'),
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

The key line is in the updated listener. After a save, getChanges() returns the attributes that changed, and getPrevious() returns the values they had before that save. Intersecting the two gives a precise diff: if only unit_price changed, only unit_price is stored, not the whole row.

Opting a model in is one line, plus an optional list of extra columns to ignore:

<?php

namespace App\Models;

use App\Models\Concerns\Auditable;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use Auditable;

    protected $fillable = ['sku', 'name', 'unit_price', 'currency', 'is_active'];

    /** Extra columns the audit trail should ignore. */
    protected array $auditExcept = ['search_vector'];
}
Enter fullscreen mode Exit fullscreen mode

The exclusion list is not cosmetic. Audit tables tend to be readable by more people than the source tables (support staff, auditors, sometimes an export to a spreadsheet). Passwords, tokens and large derived columns do not belong there.

Step 3: Record why, not just what

The most useful audit row I have ever read had a one-line reason on it. Laravel has no built-in concept of a "reason for change", so we add a tiny helper that sets it for a block of writes and always resets it afterwards:

<?php

namespace App\Support;

use Closure;

final class AuditReason
{
    private static ?string $current = null;

    public static function current(): ?string
    {
        return self::$current;
    }

    /**
     * Run a block of writes with a business reason attached to every audit row.
     */
    public static function run(string $reason, Closure $callback): mixed
    {
        $previous = self::$current;
        self::$current = $reason;

        try {
            return $callback();
        } finally {
            self::$current = $previous; // never leak into the next write
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The finally block matters. Without it, a reason set for one operation could leak into unrelated writes later in the same request or long-running worker.

For the actor and trace ID, Laravel's Context facade is a good fit. A middleware can add a trace_id to the context on every request (the Laravel docs show exactly this example), and commands or jobs can name themselves:

<?php

use Illuminate\Support\Facades\Context;

// In a console command or queued job there is no authenticated user:
Context::add('actor', 'system:price-import');
Enter fullscreen mode Exit fullscreen mode

Step 4: Using it in real code

<?php

use App\Models\Product;
use App\Support\AuditReason;
use Illuminate\Support\Facades\DB;

DB::transaction(function () use ($product) {
    AuditReason::run('Supplier price list 2026-Q4 applied', function () use ($product) {
        $product->update(['unit_price' => '14.90']);
    });
});

foreach ($product->auditLogs()->with('user')->limit(20)->get() as $log) {
    echo $log->created_at, ' ', $log->event, ' by ', $log->user?->name ?? $log->actor, PHP_EOL;
}

// Mass update that bypasses model events (no audit rows!):
Product::where('currency', 'EUR')->update(['is_active' => false]);

// Audited alternative: load and save each model in chunks.
AuditReason::run('EUR catalogue retired', function () {
    Product::where('currency', 'EUR')
        ->where('is_active', true)
        ->lazyById(500)
        ->each(fn (Product $product) => $product->update(['is_active' => false]));
});
Enter fullscreen mode Exit fullscreen mode

Notice the transaction. Because the audit row is written by a synchronous model event, it is inserted in the same database transaction as the change itself. If the transaction rolls back, the audit row rolls back with it. That is exactly what you want: no audit entries for changes that never happened, and no committed change without its audit entry.

Common pitfalls

1. Mass updates skip model events. This is the big one. The Laravel docs are explicit: when you run a mass update or delete through the query builder, the saving, saved, updating, updated, deleting and deleted events are not dispatched, because the models are never retrieved. Product::where(...)->update([...]) changes rows and writes zero audit entries. For audited models, either load and save the models in chunks (as in the lazyById example above), or write one explicit audit row describing the bulk operation. Code review is the only real defence, so make "no mass updates on audited models" a team rule.

2. Quiet saves are silent on purpose. saveQuietly(), deleteQuietly() and Model::withoutEvents() exist to skip events, which also skips your audit trail. They are fine for caches and counters, not for business data.

3. Do not defer audit writes until after commit. Laravel lets observers implement ShouldHandleEventsAfterCommit so handlers run after the transaction commits. That is great for sending emails or dispatching jobs, but for an audit trail it breaks atomicity: the change can commit and the audit write can still fail. Keep audit writes inside the transaction.

4. Soft deletes and restores. With soft deletes, a delete still fires deleted, so it is logged. A restore fires restored, which this trait does not listen to. If restores matter in your domain (they often do for customers and products), add a restored listener.

5. Unbounded growth. An audit table on a busy pricing model grows fast. Index what you actually query (the polymorphic columns are indexed by morphs()), decide a retention policy with whoever owns compliance, and archive old rows instead of deleting them silently.

6. Raw values, not formatted ones. getChanges() returns stored attribute values, so you will see "14.90" and 0, not €14.90 and "Inactive". Keep the stored values raw and format them in the screen that displays the history. Raw values are what you want when you need to replay or compare data.

Summary

An audit trail does not need a big package or a separate service to be useful. With one polymorphic table, one trait listening to created, updated and deleted, and getChanges() plus getPrevious() for precise diffs, every change to an audited model records who, when, from what and to what. A small AuditReason helper adds the why, Context adds the trace ID and system actor, and keeping the writes inside the same transaction makes the trail trustworthy.

The rules that keep it honest are just as important as the code: no mass updates or quiet saves on audited models, no after-commit audit writes, and no secrets in the log.

What is the one field in your system you wish had an audit trail the last time something went wrong?

Top comments (0)