Back to Laravel Activitylog

Customizing actions

docs/advanced-usage/customizing-actions.md

5.0.02.5 KB
Original Source

The package uses action classes for its core operations. You can extend these to customize behavior.

Available actions

LogActivityAction

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.

CleanActivityLogAction

Called by the activitylog:clean command. Handles deleting old activity records.

Overriding an action

Create a class that extends the original action and override the protected methods you want to customize:

php
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:

php
// config/activitylog.php
'actions' => [
    'log_activity' => \App\Actions\CustomLogActivityAction::class,
    'clean_log' => \Spatie\Activitylog\Actions\CleanActivityLogAction::class,
],

Manipulating changes

To modify the changes array before it's saved (e.g. removing sensitive fields), override transformChanges():

php
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);
    }
}

Overridable methods

LogActivityAction

MethodDescription
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

CleanActivityLogAction

MethodDescription
getCutOffDate($maxAgeInDays)Calculates the date before which records should be deleted
deleteOldActivities($cutOffDate, $logName)Performs the actual deletion query