Laravel 5 register middleware from in package service provider

Joren Van Hocht picture Joren Van Hocht · Apr 13, 2015 · Viewed 18.3k times · Source

I'm currently developing a package in/for Laravel 5.
My package contains a custom middleware and I would like to add it to the $routeMiddlewarearray of the Kernel class from in my package Service Provider.
But I can't seem to find a way to do this.

I tried to make a custom class that extends the Kernel class and then I can merge the array with my array.
But once out of the constructor it's not possible.

In L4 you had App::middleware, but that function is no longer available in L5.

Can anyone who has solved this problem help me solving this?

Please, tell me if my question is not clear enough, so that I can clarerify it a bit.

Answer

mitchdav picture mitchdav · Mar 24, 2017

Since Laravel 5.4 (tested up to 5.8) you would call the following line from a service provider.

$this->app['router']->aliasMiddleware('my-package-middleware', \My\Package\Middleware::class);

Or you can use the app() helper as below.

app('router')->aliasMiddleware('my-package-middleware', \My\Package\Middleware::class);