HTTP Middleware

Introduction

HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.

There are several middleware included in the Laravel framework, including middleware for maintenance, authentication, CSRF protection, and more. All of these middleware are located in the app/Http/Middleware directory.

Defining Middleware

To create a new middleware, use the make:middleware Artisan command:

  1. php artisan make:middleware AgeMiddleware

This command will place a new AgeMiddleware class within your app/Http/Middleware directory. In this middleware, we will only allow access to the route if the supplied age is greater than 200. Otherwise, we will redirect the users back to the "home" URI.

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. class AgeMiddleware
  5. {
  6. /**
  7. * Run the request filter.
  8. *
  9. * @param \Illuminate\Http\Request $request
  10. * @param \Closure $next
  11. * @return mixed
  12. */
  13. public function handle($request, Closure $next)
  14. {
  15. if ($request->input('age') <= 200) {
  16. return redirect('home');
  17. }
  18. return $next($request);
  19. }
  20. }

As you can see, if the given age is less than or equal to 200, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to "pass"), simply call the $next callback with the $request.

It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

Before / After Middleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application:

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. class BeforeMiddleware
  5. {
  6. public function handle($request, Closure $next)
  7. {
  8. // Perform action
  9. return $next($request);
  10. }
  11. }

However, this middleware would perform its task after the request is handled by the application:

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. class AfterMiddleware
  5. {
  6. public function handle($request, Closure $next)
  7. {
  8. $response = $next($request);
  9. // Perform action
  10. return $response;
  11. }
  12. }

Registering Middleware

Global Middleware

If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

Assigning Middleware To Routes

If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. For example:

  1. // Within App\Http\Kernel Class...
  2. protected $routeMiddleware = [
  3. 'auth' => \App\Http\Middleware\Authenticate::class,
  4. 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
  5. 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
  6. 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  7. ];

Once the middleware has been defined in the HTTP kernel, you may use the middleware key in the route options array:

  1. Route::get('admin/profile', ['middleware' => 'auth', function () {
  2. //
  3. }]);

Use an array to assign multiple middleware to the route:

  1. Route::get('/', ['middleware' => ['first', 'second'], function () {
  2. //
  3. }]);

Instead of using an array, you may also chain the middleware method onto the route definition:

  1. Route::get('/', function () {
  2. //
  3. })->middleware(['first', 'second']);

When assigning middleware, you may also pass the fully qualified class name:

  1. use App\Http\Middleware\FooMiddleware;
  2. Route::get('admin/profile', ['middleware' => FooMiddleware::class, function () {
  3. //
  4. }]);

Middleware Groups

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may do this using the $middlewareGroups property of your HTTP kernel.

Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to web UI and your API routes:

  1. /**
  2. * The application's route middleware groups.
  3. *
  4. * @var array
  5. */
  6. protected $middlewareGroups = [
  7. 'web' => [
  8. \App\Http\Middleware\EncryptCookies::class,
  9. \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
  10. \Illuminate\Session\Middleware\StartSession::class,
  11. \Illuminate\View\Middleware\ShareErrorsFromSession::class,
  12. \App\Http\Middleware\VerifyCsrfToken::class,
  13. ],
  14. 'api' => [
  15. 'throttle:60,1',
  16. 'auth:api',
  17. ],
  18. ];

Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware. Again, middleware groups simply make it more convenient to assign many middleware to a route at once:

  1. Route::group(['middleware' => ['web']], function () {
  2. //
  3. });

Keep in mind, the web middleware group is automatically applied to your default routes.php file by the RouteServiceProvider.

Middleware Parameters

Middleware can also receive additional custom parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create a RoleMiddleware that receives a role name as an additional argument.

Additional middleware parameters will be passed to the middleware after the $next argument:

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. class RoleMiddleware
  5. {
  6. /**
  7. * Run the request filter.
  8. *
  9. * @param \Illuminate\Http\Request $request
  10. * @param \Closure $next
  11. * @param string $role
  12. * @return mixed
  13. */
  14. public function handle($request, Closure $next, $role)
  15. {
  16. if (! $request->user()->hasRole($role)) {
  17. // Redirect...
  18. }
  19. return $next($request);
  20. }
  21. }

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

  1. Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
  2. //
  3. }]);

Terminable Middleware

Sometimes a middleware may need to do some work after the HTTP response has already been sent to the browser. For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser. To accomplish this, define the middleware as "terminable" by adding a terminate method to the middleware:

  1. <?php
  2. namespace Illuminate\Session\Middleware;
  3. use Closure;
  4. class StartSession
  5. {
  6. public function handle($request, Closure $next)
  7. {
  8. return $next($request);
  9. }
  10. public function terminate($request, $response)
  11. {
  12. // Store the session data...
  13. }
  14. }

The terminate method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of global middlewares in your HTTP kernel.

When calling the terminate method on your middleware, Laravel will resolve a fresh instance of the middleware from the service container. If you would like to use the same middleware instance when the handle and terminate methods are called, register the middleware with the container using the container's singleton method.