Laravel Middleware


Middleware in Laravel provides a mechanism for filtering HTTP requests entering your application. Middleware acts as a bridge between a request and a response, allowing you to perform actions on the request before it reaches the controller or after the response leaves the controller. This makes middleware useful for tasks such as authentication, logging, and modifying requests or responses.

Key Concepts of Middleware

  1. Creating Middleware: You can create middleware using the Artisan command-line tool. This generates a new middleware class in the app/Http/Middleware directory.

    • Create Middleware:

      php artisan make:middleware CheckAge

      This command generates a CheckAge middleware class.

  2. Middleware Structure: A middleware class typically contains two main methods: handle and terminate.

    • handle Method: This method is responsible for processing the request and determining whether to pass it further down the pipeline or return a response.

      Example:

      namespace App\Http\Middleware; use Closure; class CheckAge { public function handle($request, Closure $next) { if ($request->age < 18) { return response('You are not old enough to access this resource.', 403); } return $next($request); } }

      In this example, the handle method checks the age from the request and returns a 403 Forbidden response if the age is less than 18. Otherwise, it passes the request to the next middleware or controller.

    • terminate Method (optional): This method is called after the response has been sent to the browser. It can be used for tasks like logging.

      Example:

      public function terminate($request, $response) { // Perform some action after the response is sent }
  3. Registering Middleware: Middleware must be registered in the Laravel application before it can be used. You can register middleware globally or assign it to specific routes or route groups.

    • Global Middleware: Register middleware globally in the app/Http/Kernel.php file under the $middleware property.

      Example:

      protected $middleware = [ \App\Http\Middleware\CheckAge::class, ];
    • Route Middleware: Register middleware for specific routes in the app/Http/Kernel.php file under the $routeMiddleware property.

      Example:

      protected $routeMiddleware = [ 'checkAge' => \App\Http\Middleware\CheckAge::class, ];
  4. Using Middleware in Routes: Once registered, you can apply middleware to routes or route groups. This ensures that the middleware runs before the request reaches the controller.

    • Apply Middleware to Routes:

      Route::get('profile', 'ProfileController@show')->middleware('checkAge');
    • Apply Middleware to Route Groups:

      Route::group(['middleware' => 'checkAge'], function () { Route::get('dashboard', 'DashboardController@index'); Route::get('settings', 'SettingsController@index'); });
  5. Middleware Parameters: Middleware can accept parameters to customize its behavior. You can pass parameters when applying middleware to routes.

    • Middleware with Parameters:

      public function handle($request, Closure $next, $age) { if ($request->age < $age) { return response('You are not old enough to access this resource.', 403); } return $next($request); }
      • Apply Middleware with Parameters:
        Route::get('profile', 'ProfileController@show')->middleware('checkAge:18');
  6. Terminable Middleware: Terminable middleware is used to perform actions after the response has been sent to the client. It’s useful for tasks like logging or cleaning up resources.

    • Implement Terminable Middleware:
      use Illuminate\Contracts\Http\Kernel; class CheckAge implements TerminableMiddleware { public function handle($request, Closure $next) { // ... } public function terminate($request, $response) { // Perform actions after response is sent } }
  7. Middleware Groups: Middleware can be grouped together and applied to routes. Laravel provides predefined middleware groups such as web and api.

    • Middleware Groups:

      protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \App\Http\Middleware\AddQueuedCookiesToResponse::class, \App\Http\Middleware\ShareErrorsFromSession::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ];
    • Apply Middleware Group to Routes:

      Route::middleware('web')->group(function () { Route::get('/', 'HomeController@index'); }); Route::middleware('api')->group(function () { Route::get('users', 'UserController@index'); });
  8. Custom Middleware: You can also create custom middleware to perform specific tasks required by your application.

    • Example of Custom Middleware:
      namespace App\Http\Middleware; use Closure; class CustomMiddleware { public function handle($request, Closure $next) { // Custom logic return $next($request); } }

Summary

Middleware in Laravel is a mechanism for filtering and handling HTTP requests and responses. Its key features include:

  • Creating Middleware: Define middleware to process requests and responses.
  • Middleware Structure: Contains handle and optionally terminate methods.
  • Registering Middleware: Register middleware globally or for specific routes.
  • Using Middleware: Apply middleware to routes or route groups.
  • Middleware Parameters: Pass parameters to customize middleware behavior.
  • Terminable Middleware: Perform actions after the response is sent.
  • Middleware Groups: Group multiple middleware and apply them to routes.
  • Custom Middleware: Create and use custom middleware for specific needs.

Middleware provides a flexible way to manage cross-cutting concerns in your application, such as authentication, logging, and request modification, helping to keep your code organized and maintainable.