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.
Installation:
composer require bilfeldt/laravel-route-statistics
php artisan vendor:publish --provider="Bilfeldt\LaravelRouteStatistics\LaravelRouteStatisticsServiceProvider" --tag="migrations"
php artisan migrate
Enable Logging:
Add the middleware globally in bootstrap/app.php:
$middleware->prepend(\Bilfeldt\LaravelRouteStatistics\Http\Middleware\RouteStatisticsMiddleware::class);
First Use Case:
Run the route:stats command to inspect logged routes:
php artisan route:stats
php artisan vendor:publish --provider="Bilfeldt\LaravelRouteStatistics\LaravelRouteStatisticsServiceProvider" --tag="config"
config/routestatistics.php for:
minute, hour, day, month).App\Models\User).Global Logging:
RouteStatisticsMiddleware for all routes (simplest approach).user_id, team_id, method, route, parameters, status, ip, date, counter.Selective Logging:
Route::middleware(['routestatistics'])->group(function () {
Route::get('/admin', 'AdminController@index');
});
$request->routeStatistics(); // Enable in controllers
Contextual Data:
team_id) via middleware or request macro:
$request->routeStatistics(['team_id' => $team->id]);
Aggregation:
config/routestatistics.php:
'aggregation' => [
'interval' => 'hour', // 'minute', 'hour', 'day', 'month'
'enabled' => true,
],
Queue Logging: Enable in config to offload logging to queues:
'queue' => [
'enabled' => true,
'connection' => 'database',
],
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).Database Bloat:
'aggregation.enabled' => true) to mitigate.php artisan route:unused periodically to clean up unused routes.Middleware Placement:
RouteStatisticsMiddleware before auth middleware to log unauthenticated requests.Route Parameters:
'log_parameters' => false,
Queue Delays:
Custom User Models:
user() relationship in the config can cause user_id to log as null:
'user_model' => \App\Models\CustomUser::class,
Missing Logs:
bootstrap/app.php).$request->routeStatistics()).Incorrect Aggregation:
config/routestatistics.php for correct interval (e.g., 'hour').php artisan route:stats to validate aggregation.Performance Issues:
'aggregation.enabled' => false,
Custom Log Fields:
Extend the RouteStatistics model to add fields (e.g., device_type):
// app/Models/RouteStatistic.php
protected $casts = [
'device_type' => 'string',
];
app/Providers/RouteStatisticServiceProvider.php) to include new fields.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
}
}
Custom Aggregation Logic:
Override the aggregate() method in the RouteStatistics model for bespoke grouping.
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();
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(...);
How can I help you explore Laravel packages today?