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

Filament Activity Log Laravel Package

noxoua/filament-activity-log

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require noxoua/filament-activity-log
    php artisan vendor:publish --provider="Noxoua\FilamentActivityLog\FilamentActivityLogServiceProvider" --tag="filament-activity-log-config"
    php artisan migrate
    
    • Ensure spatie/laravel-activitylog is installed (this package extends it).
  2. Configure Activity Log Model In config/filament-activity-log.php, set your ActivityLog model (default: Spatie\Activitylog\Models\Activity).

  3. First Use Case: Log Model Events Add the HasActivityLog trait to your Eloquent model:

    use Noxoua\FilamentActivityLog\Traits\HasActivityLog;
    
    class Post extends Model
    {
        use HasActivityLog;
    }
    
    • Logs will now auto-capture create, update, delete, and restore actions.
  4. Access the Logs Panel The package adds a "Activity Log" widget to Filament’s dashboard by default. Click to view logs.


Implementation Patterns

Core Workflows

  1. Logging Custom Actions Extend logging beyond CRUD:

    use Noxoua\FilamentActivityLog\Facades\FilamentActivityLog;
    
    FilamentActivityLog::log(
        model: $user,
        action: 'flagged',
        properties: ['reason' => 'Spam'],
        description: 'User flagged for spam'
    );
    
  2. Filtering Logs in Filament Override the default log table with a custom query:

    // In a Filament resource or widget
    use Noxoua\FilamentActivityLog\Widgets\ActivityLogWidget;
    
    ActivityLogWidget::make()
        ->query(fn ($query) => $query->where('properties->status', 'published')),
    
  3. Integrating with Filament Policies Restrict log visibility by user roles:

    // In a Filament policy
    public function viewActivityLogs(User $user): bool
    {
        return $user->can('view_activity_logs');
    }
    
  4. Batch Processing Logs Use the ActivityLog model directly for bulk operations:

    $logs = ActivityLog::where('log_name', 'posts')
        ->where('properties->action', 'update')
        ->get();
    

Advanced Patterns

  1. Customizing Log Descriptions Override the default description generator:

    // In your model
    public function getActivitylogDescriptionForEvent(string $eventName): ?string
    {
        return match ($eventName) {
            'created' => "{$this->title} was created by {$this->creator->name}",
            default => parent::getActivitylogDescriptionForEvent($eventName),
        };
    }
    
  2. Adding Logs to Filament Actions Log actions triggered via Filament buttons:

    use Noxoua\FilamentActivityLog\Facades\FilamentActivityLog;
    
    $record->update([
        'status' => 'published',
    ]);
    
    FilamentActivityLog::log(
        model: $record,
        action: 'publish',
        description: "Published {$record->title}"
    );
    
  3. Real-Time Log Updates Use Laravel Echo/Pusher to notify admins of critical log events:

    // In your event listener
    event(new ActivityLogged($activityLog));
    // Broadcast via Echo/Pusher
    
  4. Exporting Logs Add a Filament action to export logs as CSV/Excel:

    use Filament\Tables\Actions\Action;
    
    Action::make('export')
        ->label('Export Logs')
        ->action(fn () => LogExporter::export(ActivityLog::all())),
    

Gotchas and Tips

Common Pitfalls

  1. Missing Migrations

    • Issue: Logs don’t appear after setup.
    • Fix: Run php artisan migrate to create the activity_logs table.
    • Tip: Verify the log_name column exists (default: spatie/laravel-activitylog uses log_name).
  2. Incorrect Model Binding

    • Issue: Logs show [object] instead of model data.
    • Fix: Ensure your model uses HasActivityLog trait and has a getActivitylogOptions() method if customizing:
      public function getActivitylogOptions(): array
      {
          return [
              'log_only' => ['created_at', 'updated_at'], // Exclude fields
              'log_name' => 'custom_posts',
          ];
      }
      
  3. Permission Denied

    • Issue: Filament widget shows "403 Forbidden".
    • Fix: Register the widget in a policy or gate:
      Gate::define('view-activity-logs', fn () => auth()->user()->can('view_activity_logs'));
      
  4. Performance with Large Logs

    • Issue: Slow queries when fetching logs.
    • Fix: Add indexes to log_name, properties, and created_at:
      Schema::table('activity_logs', function (Blueprint $table) {
          $table->index('log_name');
          $table->index('created_at');
      });
      
    • Tip: Use cursor() for pagination in Filament tables:
      ActivityLog::query()->cursor()->paginate(20);
      

Debugging Tips

  1. Log Not Triggering?

    • Check config/filament-activity-log.php for enabled set to true.
    • Verify spatie/laravel-activitylog is installed and configured.
  2. Properties Not Serializing

    • Issue: properties column shows null or malformed JSON.
    • Fix: Ensure properties are JSON-serializable (no resources, closures, or circular references).
  3. Custom Logs Overwritten

    • Issue: Default CRUD logs override custom logs.
    • Fix: Use log_only in getActivitylogOptions() to exclude default events:
      'log_only' => ['custom_action'], // Only log this
      

Extension Points

  1. Custom Log Views Override the default Filament widget:

    // In a Filament plugin
    FilamentActivityLogServiceProvider::macro('widget', fn () => CustomActivityLogWidget::make());
    
  2. Add Logs to Filament Notifications Extend the ActivityLogged event:

    event(new ActivityLogged($activityLog));
    // Listen for it in a service provider
    ActivityLogged::listen(fn ($event) => notify(new LogNotification($event->activityLog)));
    
  3. Webhook Triggers Dispatch logs to external services:

    // In ActivityLogged listener
    Http::post('https://your-webhook.com/logs', [
        'log' => $event->activityLog->toArray(),
    ]);
    
  4. Soft-Deletes in Logs Configure spatie/laravel-activitylog to log soft deletes:

    // In config/activitylog.php
    'should_log_soft_deletes' => true,
    

Pro Tips

  • Audit Trail for Filament Actions: Log all Filament form submissions:

    use Noxoua\FilamentActivityLog\Facades\FilamentActivityLog;
    
    $form->saved(function (Model $record) {
        FilamentActivityLog::log(
            model: $record,
            action: 'filament_update',
            properties: ['field' => 'title', 'old' => $oldValue, 'new' => $newValue],
        );
    });
    
  • Anonymize Sensitive Data:

    // In ActivityLog model observer
    $activityLog->properties = collect($activityLog->properties)
        ->map(fn ($value, $key) => Str::contains($key, 'password') ? '[redacted]' : $value)
        ->toArray();
    $activityLog->save();
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky