Intermediate
What is Middleware in Laravel and how is it used?
Middleware in Laravel provides a convenient mechanism for filtering HTTP requests entering your application. It allows you to execute code before or after a request is processed.
To create and use middleware, follow these steps:
- Generate middleware using:
php artisan make:middleware CheckAge
. - In the middleware, implement the
handle()
method to define the filtering logic. - Register the middleware in
app/Http/Kernel.php
.
For instance, here’s a simple middleware that checks user age:
public function handle($request, Closure $next) { return $request->age >= 18 ? $next($request) : redirect('home'); }