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 Request Analytics Laravel Package

me-shaon/laravel-request-analytics

Privacy-first web analytics for Laravel: track real-time page views, visitors, bounce rate, sessions, and performance in a built-in dashboard. Includes bot filtering, geo/device insights, data retention controls, IP anonymization, and a REST API—no third-party sharing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require me-shaon/laravel-request-analytics
    php artisan request-analytics:install
    

    The installer handles migrations, config, and assets automatically.

  2. First Use Case:

    • Access the dashboard at /analytics (or your configured path).
    • Verify real-time tracking by navigating your app—metrics like page views and visitors should update dynamically.
  3. Where to Look First:

    • Dashboard: /analytics for immediate insights.
    • Configuration: config/request-analytics.php to tweak tracking behavior (e.g., ignore paths, geolocation providers).
    • Middleware: Ensure request-analytics.access is in your web/api middleware groups for protected access.

Implementation Patterns

Core Workflows

  1. Tracking Requests:

    • The package auto-injects middleware to capture requests. No manual logging needed for standard routes.
    • For custom logic, trigger tracking manually:
      use MeShaon\RequestAnalytics\Facades\RequestAnalytics;
      
      RequestAnalytics::track($request, $customData = []);
      
  2. Queue-Based Processing:

    • Enable background processing in config/request-analytics.php:
      'queue' => [
          'enabled' => true,
          'on_queue' => 'analytics',
      ],
      
    • Dispatch jobs manually if needed:
      RequestAnalytics::dispatchTrackJob($request, $customData);
      
  3. Data Filtering:

    • Exclude paths (e.g., admin routes) in ignore-paths:
      'ignore-paths' => [
          'admin/*',
          'api/health',
      ],
      
    • Skip IPs (e.g., staging servers):
      'skip_ips' => ['192.168.1.0/24', '10.0.0.1'],
      
  4. Geolocation Integration:

    • Configure your preferred provider (e.g., MaxMind):
      'geolocation' => [
          'provider' => 'maxmind',
          'maxmind' => [
              'license_key' => env('MAXMIND_LICENSE_KEY'),
          ],
      ],
      
    • Access geo data in reports via the API:
      $visitors = RequestAnalytics::getVisitorsByCountry();
      
  5. API Access:

    • Fetch data programmatically:
      // Get top pages
      $topPages = RequestAnalytics::getTopPages(7);
      
      // Get visitor metrics
      $metrics = RequestAnalytics::getMetrics();
      

Integration Tips

  • Authentication: Use the CanAccessAnalyticsDashboard interface to gate dashboard access:
    class User implements CanAccessAnalyticsDashboard {
        public function canAccessAnalyticsDashboard(): bool {
            return $this->isAdmin();
        }
    }
    
  • Custom Reports: Extend the package’s query builder:
    use MeShaon\RequestAnalytics\Models\RequestAnalytics;
    
    $reports = RequestAnalytics::query()
        ->where('created_at', '>=', now()->subDays(7))
        ->with('user') // If tracking users
        ->get();
    
  • Event Listeners: Hook into tracking events:
    RequestAnalytics::tracked(function ($request, $data) {
        // Log custom events
    });
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Issue: Heavy traffic may slow down requests if queue processing is disabled.
    • Fix: Enable queue processing ('queue.enabled' => true) and monitor queue workers:
      php artisan queue:work --queue=analytics
      
  2. Geolocation Rate Limits:

    • Issue: Free providers (e.g., IP-API) have request limits (45/min).
    • Fix: Cache responses or switch to a paid provider (e.g., MaxMind).
  3. Middleware Conflicts:

    • Issue: request-analytics.access may conflict with other middleware (e.g., auth).
    • Fix: Reorder middleware in app/Http/Kernel.php:
      'web' => [
          \App\Http\Middleware\EncryptCookies::class,
          \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
          \Illuminate\Session\Middleware\StartSession::class,
          // ... other middleware ...
          \MeShaon\RequestAnalytics\Http\Middleware\AccessMiddleware::class, // Move to end
      ],
      
  4. IP Anonymization:

    • Issue: Anonymizing IPs (anonymize_ip: true) may break geo reports.
    • Fix: Disable anonymization if geo data is critical:
      'privacy' => ['anonymize_ip' => false],
      
  5. Pruning Side Effects:

    • Issue: Aggressive pruning (pruning.days: 30) may delete needed data.
    • Fix: Test pruning locally first:
      php artisan model:prune --model="MeShaon\RequestAnalytics\Models\RequestAnalytics" --dry-run
      

Debugging

  • Check Tracking:
    • Verify requests are logged by inspecting the request_analytics table:
      php artisan tinker
      >>> \MeShaon\RequestAnalytics\Models\RequestAnalytics::latest()->take(5)->get();
      
  • Middleware Debugging:
    • Temporarily disable middleware to isolate issues:
      'middleware' => [
          'web' => [\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class],
      ],
      
  • Queue Issues:
    • Monitor failed jobs:
      php artisan queue:failed-table
      php artisan queue:retry all
      

Extension Points

  1. Custom Metrics:

    • Extend the RequestAnalytics model to add fields:
      // app/Models/ExtendedRequestAnalytics.php
      use MeShaon\RequestAnalytics\Models\RequestAnalytics as BaseModel;
      
      class ExtendedRequestAnalytics extends BaseModel {
          protected $casts = [
              'custom_metric' => 'integer',
          ];
      }
      
    • Update migrations and config to include the new field.
  2. Custom Reports:

    • Create a service class to aggregate data:
      namespace App\Services;
      
      use MeShaon\RequestAnalytics\Models\RequestAnalytics;
      
      class CustomReport {
          public function getUserJourney($userId) {
              return RequestAnalytics::where('user_id', $userId)
                  ->orderBy('created_at')
                  ->get();
          }
      }
      
  3. Override Views:

    • Publish and modify dashboard views:
      php artisan vendor:publish --tag="request-analytics-views"
      
    • Edit files in resources/views/vendor/request-analytics/.
  4. Bot Detection:

    • Extend bot filtering by adding to the skip_referrers list or creating a custom middleware:
      namespace App\Http\Middleware;
      
      use Closure;
      use MeShaon\RequestAnalytics\Facades\RequestAnalytics;
      
      class CustomBotFilter {
          public function handle($request, Closure $next) {
              if (RequestAnalytics::isBot($request)) {
                  return response('Blocked', 403);
              }
              return $next($request);
          }
      }
      

Pro Tips

  • Local Development:
    • Skip tracking for local IPs to avoid clutter:
      'skip_ips' => ['127.0.0.1', '::1'],
      
  • Staging Environments:
    • Disable tracking entirely in staging:
      'capture' => [
          'web' => env('APP_ENV') !== 'staging',
          'api' => env('APP_ENV') !== 'staging',
      ],
      
  • Privacy Compliance:
    • Combine with Laravel’s cookie-consent package for GDPR compliance:
      // Only track if consent is given
      if (session('cookie_consent')) {
          RequestAnalytics::track($request);
      }
      
  • Monitoring:
    • Set up alerts for unusual traffic spikes using Laravel Horizon or third-party tools (e.g., Datadog).
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