Model Audit Trails with Laravel Revisionable

πŸ“– 1 minute read

When building business-critical applications, implementing model audit trails is essential for debugging and compliance. The venturecraft/revisionable package (or similar) automatically tracks all changes to Eloquent models.

Why It Matters

In production incidents, being able to answer “what was the previous value?” or “who changed this?” can save hours of investigation. Audit trails reveal the complete state transition history of a record, making it trivial to identify mistakes and determine the correct rollback state.

Key Methods

  • $model->revisions()->get() – Get all revisions
  • $revision->getDiff() – See what changed
  • $revision->executor – Who made the change
  • $revision->created_at – When it happened

Implementation

// In your model
use Venturecraft\Revisionable\RevisionableTrait;

class Order extends Model
{
    use RevisionableTrait;
    
    protected $revisionCreationsEnabled = true;
    protected $dontKeepRevisionOf = ['updated_at'];
}

// Query revision history
$order = Order::find(123);
$history = $order->revisions()->get()->map(fn($r) => [
    'timestamp' => $r->created_at->toDateTimeString(),
    'user' => $r->executor?->email,
    'changes' => $r->getDiff()
]);

// Example output:
// [
//   'timestamp' => '2026-01-30 14:37:57',
//   'user' => '[email protected]',
//   'changes' => [
//     'status' => ['old' => 'pending', 'new' => 'completed']
//   ]
// ]

Pro Tip

Store the authenticated user’s ID automatically by implementing revisionCreationsEnabled() on your model. The package will track who made each change without additional code.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *