Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 register middleware from in package service provider

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.

like image 840
Joren Van Hocht Avatar asked Apr 13 '15 07:04

Joren Van Hocht


2 Answers

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);
like image 199
mitchdav Avatar answered Sep 19 '22 10:09

mitchdav


It's about Laravel 5.6

/*In your package service provider*/
public function boot()
{
    /** @var Router $router */
    $router = $this->app['router'];
    $router->pushMiddlewareToGroup('web', MyPackage\Middleware\WebOne::class);
}
like image 29
Alexandr Shevchenko Avatar answered Sep 18 '22 10:09

Alexandr Shevchenko