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

Auditor Laravel Package

damienharper/auditor

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require damienharper/auditor
    

    Publish the config and migration:

    php artisan vendor:publish --provider="DamienHarper\Auditor\AuditorServiceProvider" --tag="auditor-config"
    php artisan vendor:publish --provider="DamienHarper\Auditor\AuditorServiceProvider" --tag="auditor-migrations"
    

    Run migrations:

    php artisan migrate
    
  2. Basic Setup Add the Auditable trait to your Eloquent model:

    use DamienHarper\Auditor\Traits\Auditable;
    
    class User extends Model
    {
        use Auditable;
    }
    
  3. First Audit Log Trigger an audit event by modifying a model:

    $user = User::find(1);
    $user->name = 'Updated Name';
    $user->save(); // Automatically logs changes
    

Where to Look First

  • Config File: config/auditor.php (adjust log retention, drivers, etc.).
  • Migrations: database/migrations/[timestamp]_create_audit_logs_table.php (customize the schema).
  • Facade: \Auditor::log() for manual logging.
  • Middleware: Use \DamienHarper\Auditor\Middleware\AuditLogs to log API requests.

Implementation Patterns

Common Workflows

  1. Automatic Model Auditing

    • Enable for all models by adding Auditable trait.
    • Customize ignored attributes in $auditIgnore:
      protected $auditIgnore = ['password', 'remember_token'];
      
  2. Manual Logging Use the facade for non-model events:

    \Auditor::log('system.event', [
        'user_id' => auth()->id(),
        'action' => 'exported_report',
        'details' => $reportData,
    ]);
    
  3. Policy-Based Auditing Restrict auditing to specific actions in policies:

    public function update(User $user, User $model)
    {
        if ($user->isAdmin()) {
            return true;
        }
        \Auditor::log('policy.violation', ['user_id' => $user->id]);
        return false;
    }
    
  4. API Request Auditing Use middleware to log HTTP requests:

    protected $middleware = [
        \DamienHarper\Auditor\Middleware\AuditLogs::class,
    ];
    

    Customize payload in AuditLogs middleware:

    public function handle($request, Closure $next)
    {
        $request->auditData = ['custom_field' => 'value'];
        return $next($request);
    }
    
  5. Batch Operations Disable auditing for bulk operations to avoid performance hits:

    \Auditor::disable();
    User::where('active', false)->update(['active' => true]);
    \Auditor::enable();
    

Integration Tips

  • Events: Listen to audit.logged for post-audit actions:
    Event::listen('audit.logged', function ($log) {
        // Send notification, trigger workflows, etc.
    });
    
  • Queues: Offload logging to a queue for high-traffic apps:
    \Auditor::setQueueConnection('database');
    
  • Soft Deletes: Extend the AuditLog model to support soft deletes:
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class AuditLog extends \DamienHarper\Auditor\Models\AuditLog
    {
        use SoftDeletes;
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Issue: Auditing every model change can slow down writes.
    • Fix: Use Auditor::disable() for bulk operations or disable for non-critical models.
  2. Ignored Attributes

    • Issue: Sensitive data (e.g., password) may still leak if not explicitly ignored.
    • Fix: Always define $auditIgnore in models:
      protected $auditIgnore = ['password', 'api_token'];
      
  3. Database Bloat

    • Issue: Unchecked audit logs can fill up the database.
    • Fix: Configure retention in config/auditor.php:
      'retention' => [
          'enabled' => true,
          'days' => 30,
      ],
      
  4. Middleware Conflicts

    • Issue: Middleware may override audit data unintentionally.
    • Fix: Merge custom data instead of replacing:
      $request->auditData = array_merge($request->auditData ?? [], ['custom_field' => 'value']);
      
  5. Custom Drivers

    • Issue: Non-database drivers (e.g., MongoDB) may not support all features.
    • Fix: Extend the Driver class or use the database driver for full functionality.

Debugging Tips

  • Log Levels: Use Auditor::log() with severity levels:
    \Auditor::log('event.name', [], 'error'); // 'info', 'warning', 'error'
    
  • Query Logging: Enable Laravel’s query log to debug slow audits:
    DB::enableQueryLog();
    $user->save();
    dd(DB::getQueryLog());
    
  • Model Events: Override retrieved, saved, etc., to debug audit triggers:
    protected static function bootAuditable()
    {
        static::saved(function ($model) {
            logger()->debug('Auditing saved model:', ['model' => $model]);
        });
    }
    

Extension Points

  1. Custom AuditLog Model Extend the base model to add fields:

    class CustomAuditLog extends \DamienHarper\Auditor\Models\AuditLog
    {
        protected $casts = [
            'metadata' => 'array',
        ];
    }
    

    Update the config:

    'model' => \App\Models\CustomAuditLog::class,
    
  2. Custom Drivers Implement DamienHarper\Auditor\Contracts\Driver for non-database storage (e.g., Elasticsearch):

    class ElasticDriver implements Driver
    {
        public function log(array $data) { /* ... */ }
    }
    

    Register in config:

    'driver' => \App\Drivers\ElasticDriver::class,
    
  3. Dynamic Ignore Attributes Use a closure to conditionally ignore attributes:

    protected $auditIgnore = [
        'password',
        function ($model) {
            return $model->isSensitive ? ['secret_key'] : [];
        },
    ];
    
  4. Audit Log Filters Add scopes to the AuditLog model for querying:

    public function scopeForModel($query, $model)
    {
        return $query->where('model', get_class($model));
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui