Laravel 5 registers middleware from service provider

I am currently developing a package for / for Laravel 5.
My package contains special middleware, and I would like to add it to the Kernel class $routeMiddleware array from my package provider.
But I can’t find a way to do this.

I tried to create my own class that extends the Kernel class, and then I can combine the array with my array.
But once from the constructor, this is impossible.

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

Can anyone who solved this problem help me solve this?

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

+14
source share
4 answers

Starting with Laravel 5.4 (tested to 5.8), you should call the next line from your service provider.

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

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

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

In the package service provider, you can access the router instance as follows:

 $this->app['router'] 

You can then register the middleware as follows:

 $this->app['router']->middleware('middlewareName', 'your\namespace\MiddlewareClass'); 

you put this code in the registration method of your service provider.

+14
source

This is 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); } 
+4
source

You can do this in two ways:

  • Register your mid-range product with your mid-tier provider.
  • Register the intermediate product inside your package. Service provider

first try one create file of your TestMiddleware.php file in your src package folder and put it somewhere, in my case I placed it inside the Middle-ware folder and then add it to your composer.json autoloader for example:

 "autoload": { "psr-4": { "Vendor\\Package\\Middleware": "packages/Vendor/Package/src/Middleware" } } 

And write your overall average:

 namespace Vendor\Package\Middleware; class TestMiddleware { public function handle( $request, Closure $next ) { echo 'hello, world!'; } } 

Then add the Tool to the main main menu of the project, in Lumen you should add it as follows:

  $app->middleware([ Vendor\Package\Middleware\TestMiddleware::class ]); 

Adding an intermediate product to a service provider

And secondly, create a medium version and upload it to the autoloader, as in the last example, and then create a service provider and register your download method in the middle:

 public function boot() { $this->app->middleware([ \Vendor\Package\Middleware\TestMiddleware::class ]); } 

And finally, you must register your service provider in your main project (Lumen example)

  $app->register(Vendor\Package\TestServiceProvider::class); 
0
source

All Articles