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

Use Artisan Commands for Testing

Integrate Artisan commands into your testing workflow to automate testing tasks and streamline the t...

Optimize Database Query Usage with Eager Loading

Use eager loading (with() method) in your controller to load related models with fewer database quer...