This is Laravel Activitylog Tutorial for Beginners. Tracking user actions is an important feature in modern web applications. Whether you want to know who updated a product, deleted a customer, or logged in, activity logs provide valuable information.
In this tutorial, you’ll learn how to use the Spatie Laravel Activitylog package to record activities in a Laravel application.
By the end of this guide, you’ll be able to:
- Install Laravel Activitylog
- Configure the package
- Log custom activities
- Automatically log model events
- View activity logs
- Customize logged data
Prerequisites
Before starting, you should have:
- PHP 8.1 or later
- Laravel 10, 11, or later
- Composer
- Basic knowledge of Laravel models and migrations
What is Laravel Activitylog?
Laravel Activitylog is a package that records activities happening inside your application.
Examples include:
- User logged in
- Product created
- Order updated
- Customer deleted
- Profile changed
Instead of creating your own logging system, this package handles it for you.
Step 1 — Install the Package
Run the following command:
composer require spatie/laravel-activitylog
Step 2 — Publish the Configuration
Publish the configuration and migration files.
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider"
This creates:
config/activitylog.php
and a migration file.
Step 3 — Run the Migration
Create the activity log table.
php artisan migrate
A table called:
activity_log
will be created.
Step 4 — Understanding the Database Table
The table stores information such as:
| Column | Description |
|---|---|
| id | Activity ID |
| log_name | Log category |
| description | Activity description |
| subject_type | Model type |
| subject_id | Model ID |
| causer_type | User model |
| causer_id | User ID |
| properties | Extra information |
| created_at | Timestamp |
Step 5 — Logging a Simple Activity
Suppose a user creates a product.
use Spatie\Activitylog\activity;
activity()
->log('Product created');
This creates a new activity entry.
Step 6 — Add a Log Name
Organize logs by category.
activity('products')
->log('Product created');
Now the log belongs to the products category.
Step 7 — Log the Authenticated User
When a logged-in user performs an action:
activity()
->causedBy(auth()->user())
->log('Updated profile');
The package records:
- User ID
- User model
- Description
Step 8 — Attach a Subject
You can associate an activity with a model.
activity()
->performedOn($product)
->log('Product updated');
Now the log is linked to the product.
Step 9 — Add Extra Properties
Store additional information.
activity()
->withProperties([
'price' => 500,
'category' => 'Electronics'
])
->log('Product created');
These values are stored as JSON.
Step 10 — Log Model Changes Automatically
Instead of manually logging every action, you can let the package do it automatically.
Example Product model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
class Product extends Model
{
use LogsActivity;
protected $fillable = [
'name',
'price',
'stock'
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly([
'name',
'price',
'stock'
]);
}
}
Now Laravel automatically logs:
- Created
- Updated
- Deleted
Step 11 — Log Only Dirty Attributes
Sometimes you only want to record fields that actually changed.
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly([
'name',
'price'
])
->logOnlyDirty();
}
Example:
Old value:
Price = 500
New value:
Price = 700
Only the changed field is logged.
Step 12 — Skip Empty Logs
Prevent logs when nothing has changed.
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnlyDirty()
->dontSubmitEmptyLogs();
}
Step 13 — Customize the Description
Provide meaningful descriptions.
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->setDescriptionForEvent(
fn(string $eventName) => "Product has been {$eventName}"
);
}
Possible results:
Product has been created
Product has been updated
Product has been deleted
Step 14 — Retrieve Activity Logs
Fetch all logs.
use Spatie\Activitylog\Models\Activity;
$activities = Activity::latest()->get();
Step 15 — Display Activity Logs
Example Blade view:
@foreach($activities as $activity)
{{ $activity->description }}
{{ $activity->created_at }}
@endforeach
Step 16 — Get Logs for a Specific Model
Retrieve logs related to a particular product.
$product->activities;
Step 17 — Get the User Who Performed the Action
$activity->causer;
Example:
John Doe
Step 18 — Access the Subject
Retrieve the related model.
$activity->subject;
Example:
Product #25
Step 19 — Read Extra Properties
$activity->properties;
Retrieve a specific value.
$activity->properties['price'];
Step 20 — Delete Old Logs
You can remove old logs manually.
Activity::where('created_at', '<', now()->subMonths(6))
->delete();
Or schedule a cleanup using Laravel’s task scheduler if your application generates many logs.
Example Controller
public function store(Request $request)
{
$product = Product::create([
'name' => $request->name,
'price' => $request->price,
'stock' => $request->stock,
]);
activity('products')
->performedOn($product)
->causedBy(auth()->user())
->withProperties([
'price' => $product->price
])
->log('Product created');
return back();
}
Best Practices
- Log only meaningful events.
- Avoid storing sensitive information such as passwords or API keys.
- Use descriptive log messages.
- Use log categories for better organization.
- Clean up old logs periodically.
- Log only changed attributes when possible.
Common Errors
Table not found
Run:
php artisan migrate
Nothing is logged
Check that:
- The package is installed.
- The migration has been executed.
- The
LogsActivitytrait is added to your model (for automatic logging). - Manual logging code is being executed.
Changes are not recorded
Ensure:
- The model uses the
LogsActivitytrait. getActivitylogOptions()is implemented correctly.- The changed attributes are included in
logOnly().
Summary
You learned how to:
- Install Laravel Activitylog.
- Publish the configuration.
- Run migrations.
- Log activities manually.
- Log model events automatically.
- Track users and models.
- Store additional properties.
- Retrieve and display activity logs.
- Optimize logging with dirty attributes and cleanup.
With these fundamentals, you can build an effective audit trail that helps monitor user actions and data changes in your Laravel applications.
