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 Auditing Log Laravel Package

onramplab/laravel-auditing-log

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require onramplab/laravel-auditing-log
    

    Run migrations to create the required database tables:

    php artisan migrate
    
  2. Publish Config: Publish the package configuration for customization:

    php artisan vendor:publish --provider="OnrampLab\LaravelAuditingLog\AuditingLogServiceProvider" --tag="config"
    

    Edit the config file at config/auditing-log.php to define your logging preferences (e.g., models to audit, log table name, etc.).

  3. First Use Case: Enable auditing for a model by adding the Auditable trait:

    use OnrampLab\LaravelAuditingLog\Traits\Auditable;
    
    class User extends Model
    {
        use Auditable;
    }
    

    Now, any changes to User records (create, update, delete) will automatically be logged.


Implementation Patterns

Core Workflows

  1. Model Auditing:

    • Attach the Auditable trait to any Eloquent model to enable auditing.
    • Customize logged fields by overriding the getAuditedAttributes() method:
      public function getAuditedAttributes()
      {
          return ['name', 'email', 'status']; // Only log these fields
      }
      
  2. Manual Logging:

    • Log custom events manually using the audit() helper or facade:
      use OnrampLab\LaravelAuditingLog\Facades\AuditingLog;
      
      AuditingLog::log('custom_event', ['key' => 'value']);
      
  3. Querying Logs:

    • Retrieve logs for a model instance:
      $user = User::find(1);
      $logs = $user->auditLogs; // Collection of audit logs
      
    • Filter logs by event type or date range:
      $logs = \OnrampLab\LaravelAuditingLog\Models\AuditLog::where('event', 'updated')
          ->whereBetween('created_at', [$startDate, $endDate])
          ->get();
      
  4. Integration with Spatie ActivityLog:

    • The package extends Spatie's ActivityLog to include additional features. Leverage Spatie's existing functionality (e.g., activity() helper) alongside this package.

Advanced Patterns

  • Soft Deletes: Enable soft deletes for audit logs by adding the SoftDeletes trait to the AuditLog model and configuring the auditing-log.php file.

  • Real-Time Notifications: Use Laravel's event system to trigger notifications when specific audit events occur:

    // In an event listener or observer
    event(new \OnrampLab\LaravelAuditingLog\Events\AuditLogged($auditLog));
    
  • Custom Log Storage: Override the default storage by binding a custom repository to the audit-log.repository service provider binding.


Gotchas and Tips

Common Pitfalls

  1. Missing Dependencies: Ensure spatie/laravel-activitylog is installed (composer require spatie/laravel-activitylog). The package relies on it for core functionality.

  2. Database Schema Mismatch: If you modify the audit_logs table manually, run php artisan vendor:publish --tag="migrations" to republish the package's migrations and update your database schema accordingly.

  3. Performance Overhead: Auditing every field on large models can impact performance. Use getAuditedAttributes() to limit logged fields:

    protected $audited = ['critical_field1', 'critical_field2']; // Explicitly define audited fields
    
  4. Event Naming Conflicts: Avoid using reserved event names (e.g., created, updated, deleted) for custom events to prevent conflicts with Eloquent's built-in events.

Debugging Tips

  • Enable Logging: Set debug to true in config/auditing-log.php to log additional debug information to Laravel's log channel.

  • Check Middleware: Ensure the AuditingLogMiddleware is registered in app/Http/Kernel.php if you're using it for route-based auditing.

  • Verify Observers: If using observers, confirm they are registered in the model's boot() method:

    class User extends Model
    {
        protected static function booted()
        {
            static::observe(\OnrampLab\LaravelAuditingLog\Observers\AuditObserver::class);
        }
    }
    

Extension Points

  1. Custom Audit Log Model: Extend the AuditLog model to add custom fields or methods:

    namespace App\Models;
    
    use OnrampLab\LaravelAuditingLog\Models\AuditLog as BaseAuditLog;
    
    class AuditLog extends BaseAuditLog
    {
        protected $casts = [
            'metadata' => 'array',
        ];
    }
    
  2. Custom Events: Create custom audit events by extending the AuditEvent class:

    namespace App\Events;
    
    use OnrampLab\LaravelAuditingLog\Events\AuditEvent;
    
    class CustomAuditEvent extends AuditEvent
    {
        public function __construct($model, $event, $changes)
        {
            parent::__construct($model, 'custom.' . $event, $changes);
        }
    }
    
  3. Hooks for Pre/Post Logging: Use the audit.logging and audit.logged events to run logic before or after an audit log is created:

    // In EventServiceProvider
    protected $listen = [
        \OnrampLab\LaravelAuditingLog\Events\AuditLogging::class => [
            \App\Listeners\LogAuditDetails::class,
        ],
    ];
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope