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
- Introduction to Spatie Laravel-Activitylog
- Installation & Setup
- Basic Usage: Logging Activities
- Tracking Model Changes
- Customizing Activity Logs
- Viewing & Querying Logs
- Advanced Features & Tips
- 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! 🚀
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.