Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Activitylog Laravel Package

spatie/activitylog

Laravel 5 user activity logging package by Spatie: records actions to a database table and optionally to Laravel’s log handler, with migration and facade support. Abandoned since 2016-06-28; use spatie/laravel-activitylog instead.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/activitylog
    

    Publish the migration:

    php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="migrations"
    

    Run the migration:

    php artisan migrate
    
  2. Basic Logging: Use the logActivity() helper in controllers or services:

    use Spatie\Activitylog\LogOptions;
    
    logActivity('User updated profile', new LogOptions());
    
  3. First Use Case: Log a model event (e.g., updated) for a User model:

    use Spatie\Activitylog\Traits\LogsActivity;
    
    class User extends Model
    {
        use LogsActivity;
    }
    

Implementation Patterns

Core Workflows

  1. Model Observers: Attach observers to models for automatic logging:

    class UserObserver extends Observer
    {
        public function saved(Model $model)
        {
            $model->logActivity('Profile updated');
        }
    }
    
  2. Customizing Logs: Override getActivityDescriptionForEvent() in models:

    public function getActivityDescriptionForEvent($event)
    {
        return "{$event}: {$this->name} (ID: {$this->id})";
    }
    
  3. Logging with Metadata: Pass additional data via LogOptions:

    logActivity('Order created', new LogOptions([
        'properties' => ['order_id' => $order->id, 'amount' => $order->amount],
    ]));
    
  4. Logging to Log Handler: Enable in config/activitylog.php:

    'log' => env('ACTIVITYLOG_LOG', false),
    
  5. Querying Logs: Use the Activity model to fetch logs:

    $logs = \Spatie\Activitylog\Models\Activity::where('subject_type', 'App\User')->latest()->get();
    

Integration Tips

  • Soft Deletes: Ensure models use SoftDeletes if tracking deleted events.
  • Events: Dispatch Laravel events and log them in listeners:
    event(new OrderCreated($order));
    // In listener: logActivity('Order created', ...);
    
  • APIs: Log API requests via middleware:
    public function handle($request, Closure $next)
    {
        logActivity('API request', new LogOptions(['properties' => $request->all()]));
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • This package is archived (EOL 2016). Use spatie/laravel-activitylog instead for Laravel 5.5+.
    • No Laravel 5.5+ support (e.g., no Eloquent events, missing features like resolvingModel()).
  2. Migration Conflicts:

    • The activities table may conflict with other packages. Check for column overlaps (e.g., properties JSON field).
  3. Performance:

    • Logging every model event (e.g., retrieved) can bloat the database. Use only in config/activitylog.php:
      'only' => ['created', 'updated', 'deleted'],
      
  4. Circular References:

    • Storing model relationships in properties may cause serialization issues. Use IDs or arrays:
      'properties' => ['user_id' => $user->id, 'tags' => $user->tags->pluck('name')],
      

Debugging

  • Missing Logs:

    • Verify the activities table exists and the logActivity() call is reached.
    • Check config/activitylog.php for only/except filters.
    • Ensure the model uses LogsActivity trait.
  • Querying Issues:

    • Use toSql() on queries to debug:
      \Spatie\Activitylog\Models\Activity::where('subject_type', 'App\User')->toSql();
      

Extension Points

  1. Custom Log Table: Override the Activity model to use a different table:

    class Activity extends \Spatie\Activitylog\Models\Activity
    {
        protected $table = 'custom_activity_logs';
    }
    
  2. Custom Log Model: Extend the Activity model to add fields:

    class Activity extends \Spatie\Activitylog\Models\Activity
    {
        protected $casts = ['ip_address' => 'string'];
    }
    
  3. Logging to External Services: Override the log() method in the ActivitylogServiceProvider to forward logs to an API or queue.

Tips

  • Audit Trails: Combine with laravel-auditlog or owen-it/auditing for richer features (e.g., diffs, nested models).
  • Anonymize Data: Sanitize sensitive data in properties before logging:
    'properties' => ['email' => str_replace('@', '[at]', $user->email)],
    
  • Testing: Use Activity::flush() to clear logs between tests:
    public function tearDown(): void
    {
        \Spatie\Activitylog\Models\Activity::flush();
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport