Middleware

Introduction

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

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.

Writing a Middleware

Let's place a new CheckAge class within your app/Http/Middleware directory or within your addon like addons/{application}/example-module/src/Http/Middleware.

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:

<?php

namespace Anomaly\ExampleModule\Http\Middleware;

use Closure;

class CheckAge
{
    
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->age <= 200) {
            return redirect('/');
        }

        return $next($request);
    }
}

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"), 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.

All middleware are resolved via the service container, so you may type-hint any dependencies you need within a middleware's constructor.{.tip}

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:

<?php

namespace Anomaly\ExampleModule\Http\Middleware;

use Closure;

class CheckAge
{
    
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}

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

<?php

namespace Anomaly\ExampleModule\Http\Middleware;

use Closure;

class CheckAge
{
    
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform action

        return $response;
    }
}

Registering Middleware

Global Middleware

If you want a middleware to run during every HTTP request to your application, list the middleware class in the $middleware property of your service provider class.

Assigning Middleware To Routes

If you would like to assign middleware to specific routes, you should define the routes with the middleware in the $middleware property of your service provider class.

protected $routes = [
    'example' => [
        'use' => 'Anomaly\ExampleModule\Http\Controller\ExampleController@method',
        'middleware' => [
            \Anomaly\ExampleModule\Http\Middleware\CheckAge::class
        ],
    ],
];

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 $groupMiddleware property of your service provider class.

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

/**
 * The addon's route middleware groups.
 *
 * @var array
 */
protected $groupMiddleware = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
    'api' => [
        'throttle:60,1',
        'auth:api',
    ],
];

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

protected $routes = [
    'example' => [
        'use' => 'Anomaly\ExampleModule\Http\Controller\ExampleController@method',
        'group' => [
            'web'
        ],
    ],
];

Out of the box, the web middleware group is automatically applied to base controller methods.{.tip}

Sorting Middleware

Rarely, you may need your middleware to execute in a specific order but not have control over their order when they are assigned to the route. In this case, you may specify your middleware priority using the middleware_priority configuration in the config/streams.php file:

    // ...
    'middleware_priority' => [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ],
    // ...

Middleware Parameters

Middleware can also receive additional 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 CheckRole middleware that receives a role name as an additional argument.

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