Eoghan O'Brien
husband · father · developer at Brightspot · lead engineer on Ignite
Home

Defining Laravel Middleware from inside a composer package

One of the problems I had recently, was to hook up some middleware from inside of a package and not via the Kernel class. In order to define middleware in a package-based Service Provider, all you really need to know is that you must get an instance of the \Illuminate\Routing\Router class and call the pushMiddlewareToGroup($group, $middleware) method.

Here's an example of how that might look inside a Service Provider:

<?php

namespace MyPackage\Providers;

use MyPackage\Http\Middleware\MyMiddleware;
use Illuminate\Support\ServiceProvider;

class MyServiceProvider extends ServiceProvider
{
    public function register()
    {
        /** \Illuminate\Routing\Router $router */
        $router = $this->app['router'];
        $router->pushMiddlewareToGroup('web', MyMiddleware::class);
    }
}

In this case, we're pushing our custom middleware onto the web stack but we could also use api or a custom group. Note, anything that's not given a web group will not have cookies, session or CSRF.