Day 1 โ€“ Setting Up User Activity Logging in Laravel#LaravelGPTAudit #LaravelAI #AuditTrail #SpatieActivityLog


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.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.