1: What is Middleware? Middleware is a mechanism for filtering HTTP requests before they reach your controllers and can modify responses before they are sent to the browser. It helps in tasks like authentication, logging, and security.
2: Creating Middleware: To create custom middleware, you can use the Artisan command make:middleware
. This generates a middleware class where you define the logic.
Example:
php artisan make:middleware CheckAge
This creates a new file in app/Http/Middleware
called CheckAge.php
.
3: Writing the Middleware Logic: In the generated middleware file, define the logic you want to execute in the handle()
method.
Example (CheckAge Middleware):
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return redirect('home');
}
return $next($request);
}
In this example, if the user’s age is less than 18, the user is redirected to the homepage.
4: Registering Middleware: To use your custom middleware, you need to register it. You can do this globally or for specific routes.
Global Middleware: In app/Http/Kernel.php
, add your middleware to the $middleware
array to apply it globally:
protected $middleware = [
\App\Http\Middleware\CheckAge::class,
];
$routeMiddleware
array:protected $routeMiddleware = [
'checkage' => \App\Http\Middleware\CheckAge::class,
];
5: Applying Middleware to Routes: You can apply middleware to specific routes or controllers by using the middleware()
method.
Example:
Route::get('profile', function () {
// Profile page content
})->middleware('checkage');
6: Passing Parameters to Middleware (Optional): Middleware can accept parameters, which makes it more flexible.
Example:
public function handle($request, Closure $next, $age)
{
if ($request->age < $age) {
return redirect('home');
}
return $next($request);
}
And in the route:
Route::get('profile', function () {
// Profile page content
})->middleware('checkage:18');
Middleware in Laravel provides an easy and efficient way to filter HTTP requests. By following these simple steps, you can create, register, and apply middleware to manage your application's request flow, ensuring proper validation, authentication, or other tasks as needed.