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

Laravel Activitylog Laravel Package

spatie/laravel-activitylog

Log user and model activity in Laravel with a simple API. Automatically record Eloquent model events, link actions to subjects and causers, store custom properties, and query a dedicated activity_log table for auditing and history.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/laravel-activitylog
    php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
    php artisan migrate
    

    (Optional: Publish config with --tag="activitylog-config")

  2. First Log Entry:

    use Spatie\Activitylog\Facades\Activity;
    
    Activity::log('User accessed dashboard');
    
  3. Query Logs:

    $logs = \Spatie\Activitylog\Models\Activity::latest()->take(10)->get();
    

First Use Case

Log a user action (e.g., model update) with automatic causer resolution:

$user = auth()->user();
$post = Post::find(1);

$post->title = 'Updated Title';
$post->save(); // Auto-logged with causer=$user

Implementation Patterns

Core Workflows

  1. Manual Logging:

    Activity::log('Custom event')
        ->performedOn($model)
        ->causedBy($user)
        ->withProperties(['ip' => request()->ip()]);
    
  2. Model Event Logging: Add use LogsActivity; to your model and configure getActivitylogOptions():

    public function getActivitylogOptions(): LogOptions {
        return LogOptions::defaults()
            ->logOnly(['title', 'status'])
            ->dontLogIfAttributesChangedOnly(['status']);
    }
    
  3. Batch Processing: Use beforeLogging hook to group activities:

    Activity::beforeLogging(function ($activity) {
        $activity->properties->put('batch_id', request()->batch_id);
    });
    

Integration Tips

  • Middleware: Set default causer in middleware:

    public function handle($request, Closure $next) {
        Activity::defaultCauser($request->user());
        return $next($request);
    }
    
  • API Responses: Attach logs to API responses:

    return response()->json([
        'data' => $post,
        'logs' => $post->activity()->latest()->take(5)->get(),
    ]);
    
  • Admin Panels: Use activity() facade in admin panels (e.g., Nova, Filament) to show audit trails.


Gotchas and Tips

Pitfalls

  1. Performance:

    • Avoid logging sensitive data (e.g., passwords) in properties.
    • Use logOnlyDirty() to reduce database writes for unchanged attributes.
  2. Causer Resolution:

    • If causer_id is null, ensure defaultCauser() is set or a CauserResolver callback is registered.
  3. UUID Models:

    • Update the migration to use Morphs with UUID fields if your models use UUIDs.
  4. Event Overrides:

    • If using Observers, ensure LogsActivity isn’t called twice (e.g., via both trait and observer).

Debugging

  • Missing Logs: Check if getActivitylogOptions() is properly defined and events (e.g., updated) are being triggered.

  • Empty Changes: Use logEmptyChanges() if you need to log events even when no attributes change.

Extension Points

  1. Custom Activity Model: Extend \Spatie\Activitylog\Models\Activity to add fields (e.g., batch_uuid):

    php artisan make:model ActivityLogExtension -m
    
  2. Log Filters: Create scopes for common queries:

    public function scopeForModel($query, $model) {
        return $query->where('subject_type', $model::class);
    }
    
  3. Webhooks: Trigger external actions (e.g., Slack alerts) via beforeLogging:

    Activity::beforeLogging(function ($activity) {
        if ($activity->description === 'Password changed') {
            Slack::alert($activity->causer, $activity->description);
        }
    });
    

Pro Tips

  • Log Names: Use different log names (e.g., admin, api) to segment activities.
  • Soft Deletes: Add softDeletes() to the Activity model if you need to purge logs.
  • Testing: Use Activity::shouldReceive('log')->once() in PHPUnit to verify logging.
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony