Engineering note · Laravel

Log Requests with Custom Middleware

By Published Updated

Laravel

Implement custom middleware to log incoming requests, helping in tracking and analyzing application traffic and performance. Use Artisan command to create a new middleware class.

CODE SAMPLE Code snippet
php artisan make:middleware LogRequestsMiddleware

Modify the handle method within the generated middleware class (LogRequestsMiddleware.php) to log incoming requests.

CODE SAMPLE Code snippet
// app/Http/Middleware/LogRequestsMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogRequestsMiddleware
{
    public function handle($request, Closure $next)
    {
        Log::info('New request: ' . $request->fullUrl());

        return $next($request);
    }
}

Register your custom middleware in the HTTP kernel (app/Http/Kernel.php).

CODE SAMPLE Code snippet
// app/Http/Kernel.php

protected $routeMiddleware = [
    // Other middleware entries...
    'log.requests' => \App\Http\Middleware\LogRequestsMiddleware::class,
];

Apply the log.requests middleware to specific routes or groups within your application.

CODE SAMPLE Code snippet
// Example usage in routes/web.php or routes/api.php

Route::middleware('log.requests')->get('/dashboard', function () {
    return view('dashboard');
});

More engineering notes

Remove Composer Package

Removing an installed Composer package from your PHP or Laravel project. Let's consider you want to...

Pass Arguments and Options to Artisan Commands

Enhance command flexibility by passing arguments and options to Artisan commands. This allows dynami...