Today’s Offer Enroll today and get access to premium content.
App Store Google Play
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:

  1. Generate middleware using: php artisan make:middleware CheckAge.
  2. In the middleware, implement the handle() method to define the filtering logic.
  3. 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'); }