Laravel Model logging using audit trail package !!

Aizaz Aziz
2 min readSep 24, 2023

--

Photo by Scott Graham on Unsplash

In Laravel, an audit trail, also known as activity logging or event logging, is a common requirement to track changes made to your application’s data. This can help you monitor user activities, troubleshoot issues, and maintain a record of all changes over time. Laravel provides various packages and approaches to implement audit trail logging.

Use the owen-it/laravel-auditing package to implement audit trail logging in your Laravel application, here's how you can do it:

By the way there is also one popular package for auditing spatie/laravel-activitylog

But I am using owen-it/laravel-auditing

install it 

composer require owen-it/laravel-auditing
Publish the Configuration File

php artisan vendor:publish --provider="OwenIt\Auditing\AuditingServiceProvider" --tag="config"

php artisan migrate

Main part:

Add Auditing to Your Models

To enable auditing for specific models, you need to add the Auditable trait to those models and specify which attributes you want to audit. For example:

use OwenIt\Auditing\Contracts\Auditable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model implements Auditable
{
use \OwenIt\Auditing\Auditable;

protected $auditInclude = [
'attribute1',
'attribute2',
// Add other attributes you want to audit here.
];
}

In this example, Post model will audit changes to the specified attributes (attribute1 and attribute2).

Time to save audit logs !!

use OwenIt\Auditing\Models\Audit;

// Log an activity when an attribute of the model changes.
$post->attribute1 = 'new value';
$post->save();

// To retrieve the audit entries for a specific model instance:
$audits = $post->audits;

// To retrieve all audit entries:
$audits = Audit::all();

Displaying Activity Logs:

@foreach($audits as $audit)
<p>{{ $audit->event }}</p>
<p>{{ $audit->old_values }}</p>
<p>{{ $audit->new_values }}</p>
<p>{{ $audit->created_at }}</p>
@endforeach

These are the essential steps to set up and use the owen-it/laravel-auditing package for audit trail logging in a Laravel application. This package provides a comprehensive auditing system with many customization options. You can refer to the package's documentation for more advanced usage and configuration options:

GitHub Repository: https://github.com/owen-it/laravel-auditing

Please note that this package offers more advanced features like custom audit events, user attribution, and more, so you can tailor the auditing behavior to your specific needs.

Thanks. Follow me for more laravel and backend articles.

--

--