Laravel 12 with Spatie Laravel-Activitylog: A Complete Guide

Author

Kritim Yantra

Apr 16, 2025

Laravel 12 with Spatie Laravel-Activitylog: A Complete Guide

In this blog post, we'll explore how to integrate and use the Spatie Laravel-Activitylog package in Laravel 12 to track user activities, log model changes, and monitor application events efficiently.


Table of Contents

  1. Introduction to Spatie Laravel-Activitylog
  2. Installation & Setup
  3. Basic Usage: Logging Activities
  4. Tracking Model Changes
  5. Customizing Activity Logs
  6. Viewing & Querying Logs
  7. Advanced Features & Tips
  8. Conclusion

1. Introduction to Spatie Laravel-Activitylog

The Spatie Laravel-Activitylog package provides an easy way to log user activities, model changes, and custom events in Laravel. Key features include:

  • Automatic model tracking (created, updated, deleted).
  • Custom activity logging (e.g., user logins, API calls).
  • Storing additional metadata (IP, user agent, changes).
  • Querying logs for analytics or debugging.

2. Installation & Setup

Step 1: Install Laravel 12

If you don’t have Laravel 12 installed:

composer create-project laravel/laravel activitylog-demo
cd activitylog-demo

Step 2: Install Spatie Laravel-Activitylog

Install the package via Composer:

composer require spatie/laravel-activitylog

Step 3: Publish & Run Migrations

Publish the migration and config file:

php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="migrations"
php artisan migrate

Publish the config file (optional):

php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="config"

3. Basic Usage: Logging Activities

Log a Custom Activity

use Spatie\Activitylog\Models\Activity;

activity()->log('User logged in');

This stores a log entry in the activity_log table.

Log with Additional Data

activity()
    ->causedBy(auth()->user()) // Associate with a user
    ->withProperties(['ip' => request()->ip()])
    ->log('User viewed dashboard');

Retrieve Logs

$activities = Activity::all();
foreach ($activities as $activity) {
    echo $activity->description; // "User logged in"
    echo $activity->causer->name; // User who triggered it
}

4. Tracking Model Changes

Automatically log created, updated, and deleted events for Eloquent models.

Step 1: Add the LogsActivity Trait

use Spatie\Activitylog\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use LogsActivity;

    protected static $logAttributes = ['title', 'content']; // Track changes to these fields
    protected static $logOnlyDirty = true; // Only log if values change
}

Step 2: Check Logged Activities

When a Post is updated:

$post = Post::find(1);
$post->update(['title' => 'New Title']);

// Retrieve logs
$lastActivity = $post->activities()->latest()->first();
echo $lastActivity->description; // "updated"
echo $lastActivity->changes; // {"old": {"title": "Old Title"}, "new": {"title": "New Title"}}

5. Customizing Activity Logs

Change Log Name

protected static $logName = 'custom_log';

Skip Logging for Certain Events

protected static $recordEvents = ['created', 'deleted']; // Skip 'updated'

Conditional Logging

public function shouldLogActivity(string $eventName): bool
{
    return $eventName === 'updated' && $this->isDirty('status');
}

6. Viewing & Querying Logs

Get Activities for a Model

$post = Post::find(1);
$activities = $post->activities;

Filter Logs

use Spatie\Activitylog\Models\Activity;

// Get all login activities
Activity::where('description', 'User logged in')->get();

// Get activities by a user
Activity::causedBy($user)->get();

Delete Old Logs

Activity::where('created_at', '<', now()->subDays(30))->delete();

7. Advanced Features & Tips

Logging in a Queue

To avoid performance issues, log activities in a queue:

// In `config/activitylog.php`
'dispatch_events_to_queue' => true,

Custom Activity Model

Extend the default Activity model:

use Spatie\Activitylog\Models\Activity;

class CustomActivity extends Activity
{
    // Custom logic
}

Update config:

'activity_model' => CustomActivity::class,

Ignoring Certain Fields

protected static $logAttributesToIgnore = ['updated_at'];

8. Conclusion

The Spatie Laravel-Activitylog package is a powerful tool for:
βœ… Tracking user actions (logins, updates).
βœ… Auditing model changes (created, updated, deleted).
βœ… Debugging & analytics (query logs for insights).

Integrate it into your Laravel 12 app today for better monitoring!

Happy logging! πŸš€

Tags

Laravel Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts

Laravel 12 Multi-Auth System: Implementing Separate Admin and User Tables
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel 12 Roles and Permissions Setup: Complete Guide
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel 12 & AdminLTE Integration: Setup Your Stunning Admin Dashboard
Kritim Yantra Kritim Yantra
Feb 28, 2025