Middleware Parameters Tutorial
What is Middleware?
Middleware is a crucial part of Laravel's architecture that acts as a bridge between a request and a response. It provides a mechanism to filter HTTP requests entering your application. Middleware can be used for various purposes such as authentication, logging, CORS, and more.
Understanding Middleware Parameters
Middleware parameters allow you to pass additional information to a middleware class. This can be useful when you want to customize the behavior of a middleware based on specific criteria. Parameters can be defined in the route file or when registering the middleware itself.
Creating Middleware with Parameters
To create a middleware that accepts parameters, you can use the Artisan command as shown below:
This command will create a new middleware class in the app/Http/Middleware
directory. Next, you can modify the generated middleware to accept a parameter.
namespace App\Http\Middleware; use Closure; class CheckAge { public function handle($request, Closure $next, $age) { if ($request->input('age') < $age) { return response('Unauthorized.', 403); } return $next($request); } }
In this example, the CheckAge
middleware checks if the input age is less than the specified parameter. If it is, an unauthorized response is returned.
Registering Middleware
After creating the middleware, you need to register it in the app/Http/Kernel.php
file. You can register it as a route middleware:
// In app/Http/Kernel.php protected $routeMiddleware = [ // Other middleware 'checkAge' => \App\Http\Middleware\CheckAge::class, ];
Using Middleware with Parameters in Routes
Once the middleware is registered, you can use it in your routes and pass parameters to it. Here’s how to apply the checkAge
middleware to a route:
// In routes/web.php Route::get('profile', function () { // Your code here })->middleware('checkAge:18');
In this example, the profile route will only be accessible if the age parameter passed to the middleware is met.
Testing the Middleware
To test the middleware, you can access the profile route with different age inputs. For example:
Conclusion
Middleware parameters in Laravel provide a powerful way to customize the behavior of your middleware. By passing parameters, you can make your middleware more dynamic and adaptable to different scenarios. This tutorial covered the creation, registration, and usage of middleware with parameters in Laravel.