spatie/laravel-activitylog

repository·main·Indexed 26 days ago

https://github.com/spatie/laravel-activitylog

A Laravel package for logging user activities and automatically tracking Eloquent model events. It stores data in an activity_log table and provides features such as manual activity logging via the activity() helper, activity buffering for high-performance environments (including Laravel Octane and Queues), and customizable causer resolution. Developers can extend core action classes like LogActivityAction and CleanActivityLogAction to customize behavior, redact sensitive data, or implement custom saving logic.

Tokens
13.7K
Snippets
50
Records
95
Agent score
91%

What's inside spatie/laravel-activitylog

  1. Enable automatic model event logging

    main

    To automatically log created, updated, and deleted events for an Eloquent model, include the Spatie\Activitylog\Models\Concerns\LogsActivity trait in your model class.

    By default, this simple implementation logs the events but does not track specific attribute changes. To track attribute changes, you must override the getActivitylogOptions() method and return an instance of LogOptions.

    use Illuminate\Database\Eloquent\Model;
    use Spatie\Activitylog\Models\Concerns\LogsActivity;
    
    class NewsItem extends Model
    {
        use LogsActivity;
    }
  2. Override core actions to customize behavior

    main

    The package uses specific action classes for its core operations. You can extend these classes and register them in your config/activitylog.php file to change how the package behaves (e.g., changing how activities are saved or how logs are cleaned).

    To override an action:

    1. Create a new class that extends the original action class.
    2. Override the specific protected methods you wish to customize.
    3. Register your new class in the actions array within config/activitylog.php.
    // 1. Create the custom action
    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());
        }
    }
    
    // 2. Register in config/activitylog.php
    'actions' => [
        'log_activity' => \App\Actions\CustomLogActivityAction::class,
        'clean_log' => \Spatie\Activitylog\Actions\CleanActivityLogAction::class,
    ],
  3. Customize model logging with getActivitylogOptions()

    main

    To control how your Eloquent models are logged, implement the getActivitylogOptions() method within your model. This method should return an instance of Spatie\Activitylog\Support\LogOptions. If you do not implement this method, the package uses default settings which log events but do not log any attribute changes.

    use Illuminate\Database\Eloquent\Model;
    use Spatie\Activitylog\Models\Concerns\LogsActivity;
    use Spatie\Activitylog\Support\LogOptions;
    
    class YourModel extends Model
    {
        use LogsActivity;
    
        public function getActivitylogOptions(): LogOptions
        {
            return LogOptions::defaults()
                ->logFillable()
                ->logOnlyDirty();
        }
    }
  4. Disable and enable logging on demand for model instances

    main

    You can prevent a specific model instance from logging activities by calling disableLogging(). This does not affect other instances of the same model. You can re-enable logging for that instance using enableLogging(). You can also chain disableLogging() with methods like update().

    $newsItem = NewsItem::create(['name' => 'original name', 'text' => 'Lorem']);
    
    // Updating with logging disabled
    $newsItem->disableLogging();
    $newsItem->update(['name' => 'The new name is not logged']);
    
    // Updating with logging enabled again
    $newsItem->enableLogging();
    $newsItem->update(['name' => 'The new name is logged']);
  5. Scope the causer for a specific block of code

    main

    Use Activity::defaultCauser() with a callback to set a temporary causer for a specific block of code. This is useful in contexts like jobs, CLI commands, or seeders where no authenticated user is present. The previous causer is automatically restored once the callback finishes execution.

    use Spatie\Activitylog\Facades\Activity;
    
    Activity::defaultCauser($admin, function () {
        $product->update(['name' => 'New name']);
        // this activity will have $admin as the causer
    });
    
    // the previous causer is restored here
  6. Group activities using a batch UUID hook

    main

    To group related activities together (for example, all activities generated during a single HTTP request), you can use the beforeLogging hook to assign a shared identifier to a custom column.

    1. Create a migration to add a batch_uuid column to your activity_log table.
    2. Generate a UUID in your Service Provider's boot method.
    3. Use the beforeLogging hook to assign that UUID to the $activity->batch_uuid property.
    // 1. Add the column via migration
    Schema::table('activity_log', function (Blueprint $table) {
        $table->uuid('batch_uuid')->nullable()->index();
    });
    
    // 2. & 3. Register the hook in AppServiceProvider::boot()
    use Illuminate\Support\Str;
    use Spatie\Activitylog\Facades\Activity;
    
    $batchUuid = (string) Str::uuid();
    
    Activity::beforeLogging(function ($activity) use ($batchUuid) {
        $activity->batch_uuid = $batchUuid;
    });
  7. Replace the removed Batch system in v5

    main

    The LogBatch class, LogBatch facade, and Activity::batch() have been removed. To group activities, use a custom property:

    $groupId = Str::uuid();
    activity()->withProperty('group', $groupId)->log('first');
    Activity::where('properties->group', $groupId)->get();