How to log route usage in Laravel from the controller

Overview

To improve our application, we need to know the basic answers to:

  • What our users are doing and when they are doing it.

  • What requests are made to our application.

  • What response is returned.

This information helps us to structure our application to better suit our users.

laravel-route-statistics package

In this shot, we will be using the laravel-route-statistics package to allow us to add user monitoring functionality from the controller.

laravel-route-statistics basically enables us to log requests and responses from our application.

Package installation

Run the following command in your command line to install the package. Ensure your network is strong during this process.


composer require bilfeldt/laravel-route-statistics

Publishing and migration

  • Step 1: vender:publish also generates the schema of the migration.

php artisan vendor:publish --provider="Bilfeldt\LaravelRouteStatistics\LaravelRouteStatisticsServiceProvider" --tag="migrations"

  • Step 2: Migrating Database: Migration sets a template table where all the logged data is stored.

php artisan migrate

  • Step 3: Publishing config file.

php artisan vendor:publish --provider="Bilfeldt\LaravelRouteStatistics\LaravelRouteStatisticsServiceProvider" --tag="config"

Code

In the example below, we implement laravel-route-statistics by calling the routeStatistics() on the $request facade, which enables the routeStatistics() method to get all requests directed to the index function of the HomeController.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller {
public function __construct() {
$this->middleware('auth');
}
public function index(Request $request) {
$request->routeStatistics(); // This will enable route statistics logging
return view('home');
}
}

Output

The output of the code is the frequency of the visited Route, which can then be displayed statistically, like so:

widget

Explanation

The above example can be seen as logging ad-hoc. This method is constrained to only the index function of the HomeController.

Free Resources