08-Mar-2024
.
Admin
Hi Dev,
In this tutorial, I'll guide you through the process of crafting custom middleware for the upcoming Laravel 11 framework.
Laravel 11 is on the horizon, bringing a host of new features and enhancements. This release boasts a more streamlined application skeleton, introducing improvements such as a refined application structure, per-second rate limiting, health routing, and more.
Middleware in Laravel acts as a filter for HTTP requests entering your application, positioned between the request and the core of your application. This strategic placement allows you to intercept, modify, or reject requests based on specific conditions. Middleware proves invaluable for tasks like authentication, logging, and request manipulation, offering a versatile approach to handling cross-cutting concerns in the HTTP lifecycle. This ensures clean and modular organization of your code.
With Laravel 11, there's a notable change in the method of registering middleware. Unlike prior versions where registration occurred in the Kernel.php file, Laravel 11 requires you to define middleware in the app.php file. To illustrate this change, let's embark on creating a "LogRequests" middleware that logs request URLs. Follow these steps to understand the process.
So let's start following step:
Step 1: Install Laravel 11
This step is not mandatory, but if you haven't yet generated the Laravel app, feel free to proceed by running the following command:
composer create-project --prefer-dist laravel/laravel laravel-dev dev-master
Step 2: Create Middleware
During this stage, let's develop the "LogRequests" middleware to record the request URL.
php artisan make:middleware LogRequests
app/Http/Middleware/LogRequests.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class LogRequests
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
// Log the incoming request
info('Incoming request: ' . $request->fullUrl());
// Continue to the next middleware or controller
return $next($request);
}
}
Step 3: Register Middleware
During this step, we'll register our custom middleware in the app.php file, as demonstrated in the following code:
bootstrap/app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'logRequests' => \App\Http\Middleware\LogRequests::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
Step 4: Apply Middleware
In this step, we will create two routes and apply the "logRequests" middleware. So, let's update the code.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['logRequests'])->group(function () {
Route::get('/example', function () {
return 'Example route';
});
Route::get('/example-2', function () {
return 'Example route 2';
});
});
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/example
http://localhost:8000/example-2
Output:
[2024-03-06 10:42:43] local.INFO: Incoming request: http://localhost:8000/example
[2024-03-06 10:42:46] local.INFO: Incoming request: http://localhost:8000/example-2
I hope it can help you...
#Laravel 11