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.
php artisan make:middleware LogRequestsMiddleware
Modify the handle method within the generated middleware class (LogRequestsMiddleware.php) to log incoming requests.
// 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).
// 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.
// Example usage in routes/web.php or routes/api.php
Route::middleware('log.requests')->get('/dashboard', function () {
return view('dashboard');
});
You Might Also Like
Use Lazy Eager Loading for Conditional Relationships
Load related models only when needed using lazy eager loading. This technique helps in optimizing qu...
Handling Dates with Carbon Date Helpers
# Example 1: Getting the Current Date and Time You can easily get the current date and time using Ca...