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 Route Statistics Laravel Package

bilfeldt/laravel-route-statistics

Logs Laravel route usage statistics by recording and aggregating requests/responses per route, user, and timeframe (hour/day/month) to minimize database storage. Helps spot heavy users, high-traffic endpoints, and suspicious unauthenticated activity.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bilfeldt/laravel-route-statistics
    php artisan vendor:publish --provider="Bilfeldt\LaravelRouteStatistics\LaravelRouteStatisticsServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. Enable Logging: Add the middleware globally in bootstrap/app.php:

    $middleware->prepend(\Bilfeldt\LaravelRouteStatistics\Http\Middleware\RouteStatisticsMiddleware::class);
    
  3. First Use Case: Run the route:stats command to inspect logged routes:

    php artisan route:stats
    

Key Configuration

  • Publish the config file for customization:
    php artisan vendor:publish --provider="Bilfeldt\LaravelRouteStatistics\LaravelRouteStatisticsServiceProvider" --tag="config"
    
  • Configure config/routestatistics.php for:
    • Aggregation intervals (minute, hour, day, month).
    • Custom user model (if not App\Models\User).
    • Queue logging for performance.

Implementation Patterns

Core Workflows

  1. Global Logging:

    • Use RouteStatisticsMiddleware for all routes (simplest approach).
    • Logs: user_id, team_id, method, route, parameters, status, ip, date, counter.
  2. Selective Logging:

    • Apply middleware to specific routes/groups:
      Route::middleware(['routestatistics'])->group(function () {
          Route::get('/admin', 'AdminController@index');
      });
      
    • Use request macro for conditional logging:
      $request->routeStatistics(); // Enable in controllers
      
  3. Contextual Data:

    • Attach custom context (e.g., team_id) via middleware or request macro:
      $request->routeStatistics(['team_id' => $team->id]);
      
  4. Aggregation:

    • Configure aggregation in config/routestatistics.php:
      'aggregation' => [
          'interval' => 'hour', // 'minute', 'hour', 'day', 'month'
          'enabled'  => true,
      ],
      
    • Reduces database load by grouping identical requests.

Integration Tips

  • Queue Logging: Enable in config to offload logging to queues:

    'queue' => [
        'enabled' => true,
        'connection' => 'database',
    ],
    
    • Useful for high-traffic apps to avoid blocking requests.
  • Custom Models: Override the default RouteStatistics model by setting model in config:

    'model' => \App\Models\CustomRouteStatistic::class,
    
  • API/Web Segmentation: Use scopes to filter logs:

    RouteStatistics::whereApi()->get(); // API routes only
    RouteStatistics::whereWeb()->get(); // Web routes only
    
  • Artisan Commands:

    • route:stats: View aggregated stats for specific routes.
    • route:unused: Identify unused routes (requires prior logging).

Gotchas and Tips

Pitfalls

  1. Database Bloat:

    • Without aggregation, logs can grow rapidly. Enable aggregation ('aggregation.enabled' => true) to mitigate.
    • Run php artisan route:unused periodically to clean up unused routes.
  2. Middleware Placement:

    • Place RouteStatisticsMiddleware before auth middleware to log unauthenticated requests.
    • If placed after auth, guest routes won’t log user data.
  3. Route Parameters:

    • Parameters are logged by default (v4.0+). Disable in config if sensitive:
      'log_parameters' => false,
      
  4. Queue Delays:

    • If using queues, ensure the queue worker processes logs promptly to avoid discrepancies in stats.
  5. Custom User Models:

    • Forgetting to update the user() relationship in the config can cause user_id to log as null:
      'user_model' => \App\Models\CustomUser::class,
      

Debugging

  • Missing Logs:

    • Verify middleware is registered (check bootstrap/app.php).
    • Ensure the request macro is called (e.g., $request->routeStatistics()).
  • Incorrect Aggregation:

    • Check config/routestatistics.php for correct interval (e.g., 'hour').
    • Run php artisan route:stats to validate aggregation.
  • Performance Issues:

    • Disable aggregation temporarily to test raw logging speed:
      'aggregation.enabled' => false,
      
    • Monitor queue backlogs if using queued logging.

Extension Points

  1. Custom Log Fields: Extend the RouteStatistics model to add fields (e.g., device_type):

    // app/Models/RouteStatistic.php
    protected $casts = [
        'device_type' => 'string',
    ];
    
    • Update the factory (app/Providers/RouteStatisticServiceProvider.php) to include new fields.
  2. Event Listeners: Trigger actions on log creation (e.g., notify admins of high traffic):

    // app/Listeners/LogHighTraffic.php
    public function handle(RouteStatisticsCreated $event) {
        if ($event->statistic->counter > 1000) {
            // Notify admin
        }
    }
    
  3. Custom Aggregation Logic: Override the aggregate() method in the RouteStatistics model for bespoke grouping.

  4. API for Analytics: Build a dashboard using the RouteStatistics model:

    // Example: Get top 5 most-used routes
    RouteStatistics::selectRaw('route, sum(counter) as total')
        ->groupBy('route')
        ->orderBy('total', 'desc')
        ->limit(5)
        ->get();
    

Pro Tips

  • Exclude Routes: Use middleware negation to skip logging for specific routes:

    Route::middleware(['routestatistics', 'except' => ['healthcheck']])->group(...);
    
  • Retention Policy: Add a scheduled task to purge old logs (e.g., older than 6 months):

    // app/Console/Commands/PurgeOldLogs.php
    RouteStatistics::where('date', '<=', now()->subMonths(6))->delete();
    
  • Team-Based Analytics: Use the team_id field to track usage per team:

    RouteStatistics::where('team_id', $team->id)->get();
    
  • Health Checks: Exclude /health routes from logging to reduce noise:

    Route::middleware(['routestatistics', 'except' => ['health']])->group(...);
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor