HTTP Middleware

    HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Lumen 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.

    All middleware should be stored in the directory.

    To create a new middleware, copy the ExampleMiddleware that is included with the default Lumen application. In our new 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.

    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.

    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. public function handle($request, Closure $next)
    6. {
    7. $response = $next($request);
    8. // Perform action
    9. return $response;
    10. }
    11. }

    If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the call to the $app->middleware() method in your bootstrap/app.php file:

    If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in bootstrap/app.php file's call to the $app->routeMiddleware() method:

    1. $app->routeMiddleware([
    2. 'auth' => App\Http\Middleware\Authenticate::class,
    3. ]);

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

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

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

    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. $app->put('post/{id}', ['middleware' => 'role:editor', function ($id) {
    2. }]);

    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 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:

    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 middleware in your bootstrap/app.php file.