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 User Monitoring Laravel Package

binafy/laravel-user-monitoring

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require binafy/laravel-user-monitoring
    php artisan vendor:publish --provider="Binafy\UserMonitoring\UserMonitoringServiceProvider"
    php artisan migrate
    
    • Publishes config (config/usermonitoring.php) and migrations (creates user_monitoring table).
  2. First Use Case:

    • Track a user action (e.g., a form submission):
      use Binafy\UserMonitoring\Facades\UserMonitoring;
      
      UserMonitoring::track('user.submitted.form', [
          'form_id' => $form->id,
          'user_id' => auth()->id(),
          'metadata' => ['ip' => request()->ip()]
      ]);
      
    • View tracked events in the admin panel (if configured) or via:
      $events = \Binafy\UserMonitoring\Models\UserMonitoring::latest()->take(10)->get();
      
  3. Where to Look First:

    • Config File: config/usermonitoring.php (adjust enabled, models, and middleware).
    • Middleware: Add to app/Http/Kernel.php under $routeMiddleware:
      'track.user' => \Binafy\UserMonitoring\Http\Middleware\TrackUser::class,
      
      Then apply to routes:
      Route::middleware(['auth', 'track.user'])->group(function () { ... });
      
    • Models: Extend \Binafy\UserMonitoring\Models\UserMonitoring if custom fields are needed.

Implementation Patterns

Core Workflows

  1. Automatic Tracking:

    • Use the TrackUser middleware to log all authenticated requests:
      Route::middleware(['auth', 'track.user'])->group(function () {
          Route::get('/dashboard', [DashboardController::class, 'index']);
      });
      
    • Customize tracked data in app/Providers/UserMonitoringServiceProvider.php:
      public function boot()
      {
          UserMonitoring::extend(function ($event) {
              $event->ip = request()->ip();
              $event->userAgent = request()->userAgent();
          });
      }
      
  2. Manual Tracking:

    • Log specific events (e.g., API calls, cron jobs):
      UserMonitoring::track('api.payment.processed', [
          'payment_id' => $payment->id,
          'amount' => $payment->amount,
          'status' => $payment->status
      ]);
      
    • Use tags for categorization:
      UserMonitoring::track('user.viewed.profile', [], ['tag' => 'profile']);
      
  3. Querying Events:

    • Filter events by user, action, or metadata:
      // Events for a specific user
      $userEvents = UserMonitoring::where('user_id', auth()->id())->get();
      
      // Events with a specific tag
      $profileEvents = UserMonitoring::where('tags', 'like', '%"tag":"profile"%')->get();
      
    • Use scopes for reusable queries:
      // Add to UserMonitoring model
      public function scopeForAction($query, $action)
      {
          return $query->where('action', $action);
      }
      
  4. Integration with Notifications:

    • Trigger alerts for critical events (e.g., failed logins):
      UserMonitoring::track('auth.failed.login', [
          'user_id' => $user->id,
          'ip' => request()->ip()
      ], [], function ($event) {
          Notification::route('mail', $event->user->email)
                      ->notify(new FailedLoginAlert($event));
      });
      
  5. Admin Panel:

    • Use the built-in Blade views (resources/views/vendor/usermonitoring/...) or extend them.
    • Example route (add to routes/web.php):
      Route::middleware(['auth', 'admin'])->get('/monitoring', [MonitoringController::class, 'index']);
      

Advanced Patterns

  1. Custom Event Models:

    • Extend the base model for domain-specific needs:
      class CustomEvent extends \Binafy\UserMonitoring\Models\UserMonitoring
      {
          protected $casts = [
              'metadata' => 'json',
              'tags' => 'json',
          ];
      
          public function scopeForPayment($query)
          {
              return $query->where('action', 'like', '%payment%');
          }
      }
      
    • Update config to use your model:
      'model' => \App\Models\CustomEvent::class,
      
  2. Batch Processing:

    • Process large volumes of events efficiently:
      $events = UserMonitoring::query()->limit(1000)->get();
      foreach ($events as $event) {
          // Analyze or export data
      }
      
  3. Exporting Data:

    • Export events to CSV/Excel:
      use Maatwebsite\Excel\Facades\Excel;
      
      Excel::download(new UserMonitoringExport, 'user-monitoring.csv');
      
    • Create a custom export class:
      class UserMonitoringExport implements FromCollection
      {
          public function collection()
          {
              return UserMonitoring::all();
          }
      
          public function headings(): array
          {
              return ['ID', 'Action', 'User ID', 'Created At'];
          }
      
          public function map($event): array
          {
              return [
                  $event->id,
                  $event->action,
                  $event->user_id,
                  $event->created_at->format('Y-m-d H:i:s'),
              ];
          }
      }
      
  4. Real-Time Monitoring:

    • Use Laravel Echo/Pusher to broadcast events:
      UserMonitoring::track('user.online', [], [], function ($event) {
          broadcast(new UserActivityBroadcast($event))->toOthers();
      });
      

Gotchas and Tips

Common Pitfalls

  1. Performance Overhead:

    • Issue: Tracking every request may slow down high-traffic routes.
    • Fix:
      • Disable for non-critical routes:
        Route::middleware(['auth', 'track.user'])->group(function () {
            // Exclude API routes if not needed
        });
        
      • Use queue jobs for async logging:
        UserMonitoring::track('user.action', [], [], function ($event) {
            TrackEventJob::dispatch($event);
        });
        
      • Configure config/usermonitoring.php:
        'enabled' => env('APP_ENV') !== 'production', // Disable in prod if needed
        
  2. Metadata Serialization:

    • Issue: Complex objects (e.g., Eloquent models) may not serialize correctly.
    • Fix: Cast metadata to JSON explicitly:
      UserMonitoring::track('user.created.post', [
          'post' => $post->toArray(), // Convert to array first
      ]);
      
    • Or extend the model:
      protected $casts = [
          'metadata' => 'json',
      ];
      
  3. Middleware Conflicts:

    • Issue: TrackUser middleware may interfere with other middleware (e.g., auth).
    • Fix: Order matters in app/Http/Kernel.php:
      protected $middleware = [
          // ...
          \Binafy\UserMonitoring\Http\Middleware\TrackUser::class,
      ];
      
    • Or conditionally apply middleware:
      Route::middleware(['auth'])->group(function () {
          Route::middleware(['track.user'])->group(function () {
              // Only track these routes
          });
      });
      
  4. Database Bloat:

    • Issue: Unchecked tracking can fill the database with redundant data.
    • Fix:
      • Set up retention policies (e.g., delete events older than 6 months):
        // Run via a scheduled job
        UserMonitoring::where('created_at', '<=', now()->subMonths(6))->delete();
        
      • Use partitioning or archiving for large datasets.
  5. User Privacy:

    • Issue: Storing PII (Personally Identifiable Information) may violate GDPR/CCPA.
    • Fix:
      • Anonymize sensitive data:
        UserMonitoring::extend(function ($event) {
            $event->metadata['email'] = strtok(auth()->user()->email, '@');
        });
        
      • Add a sensitive flag to metadata:
        UserMonitoring::track('user.viewed.profile', [
            'sensitive_data' => ['email' => auth()->user()->email],
        ], [], function ($event) {
            // Encrypt or hash sensitive fields
        });
        

Debugging Tips

  1. Log Levels:
    • Adjust logging verbosity in config/usermonitoring.php:
      'log_level' => 'debug', // Options: debug, info, warning, error
      
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager