On this page
- Why Activity Logging Matters
- Key Features of Spatie Laravel Activitylog
- Installation and Setup in Laravel 12
- Basic Logging Techniques
- Simple Activity Logging
- Context-Rich Logging
- Automatic Model Event Tracking
- Retrieving and Managing Activity Logs
- Displaying Logs in Views
- Cleaning Up Old Logs
- Conclusion
Hello Laravel developers! In this comprehensive guide, we’ll explore how to implement detailed activity tracking in Laravel 12 using the powerful spatie/laravel-activitylog package. Whether you need to monitor user actions for security compliance, debug issues, or understand user behavior, this package provides an elegant solution to log every important activity directly to your database.
Why Activity Logging Matters
Imagine this scenario: a user reports that their critical data has mysteriously disappeared, or your manager asks who changed important system settings overnight. Without proper activity logs, you’re left guessing. Effective logging provides:
- Accountability: Track exactly who did what and when
- Debugging: Identify the steps that led to errors or unexpected behavior
- Security: Detect suspicious activities and potential breaches
- Compliance: Meet regulatory requirements for data access and modification
- User insights: Understand which features people actually use
The Spatie Activity Log package transforms Laravel’s basic logging into a structured tracking system that stores activities with their complete context — who caused them, what they affected, and what changed.
Key Features of Spatie Laravel Activitylog
- Automatic model event tracking — log created, updated, and deleted events
- Flexible contextual logging — associate activities with users and models
- Custom property storage — add any additional data you need
- Simple retrieval — query logs using Eloquent
- Frontend-ready — easily display logs in your admin panels
Installation and Setup in Laravel 12
Step 1: Create a New Laravel 12 Project
composer create-project laravel/laravel laravel12-activitylogs
cd laravel12-activitylogsStep 2: Install the Activity Log Package
composer require spatie/laravel-activitylogStep 3: Publish and Run Migrations
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
php artisan migrateThis creates the activity_log table that will store all your activity records.
Step 4: (Optional) Publish the Configuration File
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-config"The config file (config/activitylog.php) allows you to customize various aspects of the package:
'enabled' => env('ACTIVITY_LOGGER_ENABLED', true),
'delete_records_older_than_days' => 365,
'default_log_name' => 'default',Basic Logging Techniques
Simple Activity Logging
The most basic way to log an activity:
activity()->log('User viewed the dashboard');This creates a log entry with the description “User viewed the dashboard” and automatically associates it with the currently authenticated user.
Context-Rich Logging
Here’s a more practical example with full context:
activity()
->performedOn($user)
->causedBy(auth()->user())
->withProperties([
'ip' => request()->ip(),
'user_agent' => request()->userAgent(),
'previous_url' => url()->previous()
])
->log('updated_profile');Let’s break down the methods:
performedOn($model): Specifies which model was affectedcausedBy($user): Indicates who performed the actionwithProperties($array): Stores any custom data you needlog($description): Records the activity with your description
Automatic Model Event Tracking
One of the most powerful features is automatically logging model events. To enable this, add the LogsActivity trait to your model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
class Post extends Model
{
use LogsActivity;
protected $fillable = ['title', 'content', 'status'];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['title', 'status'])
->logOnlyDirty()
->setDescriptionForEvent(fn(string $eventName) => "Post was {$eventName}");
}
}Now when you create, update, or delete a Post, it’s automatically logged:
$post = Post::create(['title' => 'My First Post', 'content' => 'Lorem ipsum']);
// Logs: "Post was created" with the new attributes
$post->update(['title' => 'Updated Title']);
// Logs: "Post was updated" showing only the changed fieldsRetrieving and Managing Activity Logs
Accessing Logs
Since activities are stored using Eloquent, you can query them like any other model:
use Spatie\Activitylog\Models\Activity;
// Get all activities
$activities = Activity::all();
// Get latest activity
$lastLoggedActivity = Activity::all()->last();
$lastLoggedActivity->subject;
$lastLoggedActivity->causer;
$lastLoggedActivity->getExtraProperty('customProperty');
$lastLoggedActivity->description;Displaying Logs in Views
Create a simple view to display activities:
// In your controller
public function index()
{
$activities = Activity::with(['causer'])
->latest()
->paginate(20);
return view('activities.index', compact('activities'));
}<!-- resources/views/activities/index.blade.php -->
<table class="min-w-full divide-y divide-gray-200">
<thead>
<tr>
<th>Description</th>
<th>User</th>
<th>Subject</th>
<th>Date</th>
</tr>
</thead>
<tbody>
@foreach($activities as $activity)
<tr>
<td>{{ $activity->description }}</td>
<td>{{ $activity->causer->name ?? 'System' }}</td>
<td>{{ class_basename($activity->subject_type) }}</td>
<td>{{ $activity->created_at->format('M j, Y g:i A') }}</td>
</tr>
@endforeach
</tbody>
</table>Cleaning Up Old Logs
To prevent your database from growing indefinitely, automatically clean up old logs:
// routes/console.php
$schedule->command('activitylog:clean')->daily();
// Or clean logs older than 7 days
// $schedule->command('activitylog:clean --days=7')->daily();You can also run this manually:
php artisan activitylog:clean --days=30Conclusion
The Spatie Laravel Activitylog package transforms how you track user activities in your Laravel 12 applications. From simple action logging to comprehensive model change tracking, it provides everything you need to maintain complete visibility over what’s happening in your application.
The key benefits we’ve covered:
- ✅ Easy setup — just install, migrate, and start logging
- ✅ Automatic model tracking — monitor created, updated, and deleted events
- ✅ Rich context — know who did what, when, and what changed
- ✅ Flexible querying — easily retrieve and filter activities
- ✅ Customizable — adapt to your specific needs
By implementing activity logs, you’re not just building features — you’re building auditability, security, and maintainability into your application’s foundation.
If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel
Free resources for this topic
Code snippets and fixes for this topic
Get one practical tip every week
New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.
Free download: Laravel interview questions (PDF)
Have a question about this post?
Ask the community: other developers and the author can answer.
Get notified about new articles
One click, no email needed. Turn it off anytime with the bell at the top.
Get new articles on your iPhone
Add DEV Talk to your Home Screen, open it, then tap the bell.
Enjoying the content?
If this article helped you, you can support the author with a coffee. It keeps new posts coming.
Comments 1
Guest
Great !!