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

Simple Laravel Audit Laravel Package

motomedialab/simple-laravel-audit

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require motomedialab/simple-laravel-audit
    php artisan migrate
    

    This creates the audit_logs table and sets up the package.

  2. First Use Case: Trigger an audit log for a model update in a controller or service:

    use Motomedialab\SimpleLaravelAudit\Facades\Audit;
    
    // Example: Audit a user update
    Audit::log('users.update', $user, 'Updated user profile', ['old_email' => $user->old_email]);
    
  3. Where to Look First:

    • Facade: Motomedialab\SimpleLaravelAudit\Facades\Audit (primary entry point).
    • Config: Publish with php artisan vendor:publish --provider="Motomedialab\SimpleLaravelAudit\AuditServiceProvider" to customize table names, IP resolution, or user resolution.
    • Migrations: Check database/migrations/[timestamp]_create_audit_logs_table.php for schema details.

Implementation Patterns

Core Workflows

  1. Model Events: Bind to Eloquent events (e.g., saved, deleted) to auto-audit changes:

    use Motomedialab\SimpleLaravelAudit\Facades\Audit;
    
    $user->saved(function ($model) {
        Audit::log('users.created', $model, 'User created via registration');
    });
    
  2. Manual Logging: Log custom actions (e.g., API calls, admin actions):

    Audit::log(
        'admin.action',
        auth()->user(),
        'Deleted 5 inactive users',
        ['count' => 5, 'model' => 'User']
    );
    
  3. FilamentPHP Integration: Use the HasAuditLogs trait in Filament resources to display audit trails:

    use Motomedialab\SimpleLaravelAudit\Filament\HasAuditLogs;
    
    class UserResource extends Resource {
        use HasAuditLogs;
        // ...
    }
    
  4. Batch Operations: Audit bulk actions (e.g., imports) with a single log entry:

    Audit::log('import.users', auth()->user(), 'Imported 100 users', ['file' => 'users.csv']);
    

Integration Tips

  • Middleware: Log requests globally via middleware:
    public function handle(Request $request, Closure $next) {
        Audit::log('http.request', auth()->user(), $request->path(), ['method' => $request->method()]);
        return $next($request);
    }
    
  • Queues: Offload audit logging to a queue for performance:
    Audit::queue()->log('slow.process', $user, 'Processed large dataset');
    
  • Custom Resolvers: Override default user/IP resolution in config:
    'user_resolver' => function () {
        return auth()->guard('admin')->user();
    },
    

Gotchas and Tips

Pitfalls

  1. Performance:

    • Avoid logging in tight loops (e.g., iterating 10K records). Use batch logging or queues.
    • Disable logging for non-critical actions in development:
      if (app()->environment('production')) {
          Audit::log('critical.action', $user, '...');
      }
      
  2. Data Leakage:

    • Sensitive data (passwords, tokens) may accidentally be logged. Sanitize payloads:
      Audit::log('users.update', $user, 'Updated profile', [
          'old_email' => $user->old_email,
          'new_email' => str_replace('*@*.com', '***@***.com', $user->email),
      ]);
      
  3. Filament Caching:

    • Audit logs in Filament may not update in real-time due to caching. Clear cache after bulk operations:
      php artisan filament:cache-clear
      
  4. Model Binding:

    • Ensure logged models are serializable. Avoid logging closures or resources directly.

Debugging

  • Missing Logs:

    • Check if the audit_logs table exists and is writable.
    • Verify the event name (e.g., 'users.update') matches your config or queries.
    • Enable debug mode in config:
      'debug' => env('APP_DEBUG', false),
      
  • IP Resolution:

    • If IPs appear as ::1 or 127.0.0.1, override the ip_resolver in config:
      'ip_resolver' => function () {
          return request()->ip() ?? 'external';
      },
      

Extension Points

  1. Custom Fields: Add columns to the audit_logs table via a migration:

    Schema::table('audit_logs', function (Blueprint $table) {
        $table->string('custom_field')->nullable();
    });
    

    Then extend the Audit facade to include it:

    Audit::log('custom.event', $user, 'Action', [], ['custom_field' => 'value']);
    
  2. Event Subscribers: Listen to audit.logged events to process logs asynchronously:

    Event::listen(AuditLogged::class, function (AuditLogged $event) {
        // Send notification, update analytics, etc.
    });
    
  3. Soft Deletes: Exclude soft-deleted models from audit logs by overriding the shouldAudit method in your model:

    public function shouldAudit(): bool {
        return !$this->isSoftDeleted();
    }
    
  4. Localization: Translate log messages using Laravel’s translation system:

    Audit::log('users.update', $user, __('audit.users.updated'));
    
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