To build an AI-powered audit trail, we first need to log every user action in Laravel. The best tool for this is Spatie Activity Log.
๐งฉ Step 1: Install the package
composer require spatie/laravel-activitylog
Then publish the config and migration:
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
php artisan migrate
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-config"
โ๏ธ Step 2: Configure the logger
In config/activitylog.php
, you can tweak settings like:
'log_name' => 'default',
'events' => ['created', 'updated', 'deleted'],
๐ง Step 3: Add LogsActivity
to your models
In any model you want to audit (e.g., Customer
, Vehicle
, VehiclePackageRenewal
):
use Spatie\Activitylog\Traits\LogsActivity;
class VehiclePackageRenewal extends Model
{
use LogsActivity;
protected static $logAttributes = ['start_date', 'end_date', 'status', 'price'];
protected static $logOnlyDirty = true;
protected static $logName = 'renewal';
public function getDescriptionForEvent(string $eventName): string
{
return "Renewal was {$eventName}";
}
}
๐ค Step 4: Ensure user is attached
Make sure the authenticated user is logged by setting this in your middleware or AppServiceProvider
:
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Models\Activity;
Activity::saving(function (Activity $activity) {
if (Auth::check()) {
$activity->causer_id = Auth::id();
$activity->causer_type = Auth::user()::class;
}
});
๐ Optional: Customize
causer
globally if you’re using multiple guards.
๐ Step 5: View logs in Tinker
Test your changes:
php artisan tinker
>>> \Spatie\Activitylog\Models\Activity::latest()->first()
You should see entries like:
"description" => "Renewal was updated"
"causer" => App\Models\User { name: "Admin" }
"properties" => [ old => [...], attributes => [...] ]
โ Tomorrow (Day 2), weโll build an interactive log viewer dashboard.