spatie/laravel-activitylog
Log user and model activity in Laravel with a simple API. Automatically record Eloquent events, track subjects and causers, attach custom properties, and query everything via the Activity model. Stores logs in the activity_log table.
The package uses action classes for its core operations. You can extend these to customize behavior.
Called every time an activity is logged. Handles description placeholder replacement, transforming changes, calling beforeActivityLogged() on the subject, and saving the activity to the database.
Called by the activitylog:clean command. Handles deleting old activity records.
Create a class that extends the original action and override the protected methods you want to customize:
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Actions\LogActivityAction;
class CustomLogActivityAction extends LogActivityAction
{
protected function save(Model $activity): void
{
// Example: dispatch to queue instead of saving synchronously
dispatch(fn () => $activity->save());
}
}
Then register it in the config:
// config/activitylog.php
'actions' => [
'log_activity' => \App\Actions\CustomLogActivityAction::class,
'clean_log' => \Spatie\Activitylog\Actions\CleanActivityLogAction::class,
],
To modify the changes array before it's saved (e.g. removing sensitive fields), override transformChanges():
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Spatie\Activitylog\Actions\LogActivityAction;
class RedactPasswordAction extends LogActivityAction
{
protected function transformChanges(Model $activity): void
{
$changes = $activity->attribute_changes?->toArray() ?? [];
Arr::forget($changes, ['attributes.password', 'old.password']);
$activity->attribute_changes = collect($changes);
}
}
| Method | Description |
|---|---|
resolveDescription($activity, $description) |
Resolves placeholders like :subject.name in the description |
transformChanges($activity) |
Modify the changes array before saving (default: no-op) |
beforeActivityLogged($activity) |
Calls beforeActivityLogged() on the subject model if it exists |
save($activity) |
Saves the activity to the database |
replacePlaceholders($description, $activity) |
Performs the actual placeholder replacement |
| Method | Description |
|---|---|
getCutOffDate($maxAgeInDays) |
Calculates the date before which records should be deleted |
deleteOldActivities($cutOffDate, $logName) |
Performs the actual deletion query |
How can I help you explore Laravel packages today?