I am developing some middleware for my custom package. However, in order to use those package middleware, I have to manually add it in to kernel.php
file into $routeMiddleware
. So now, I have to manually add in these few extra line of code everytime when using my package.
'login.auth' => \Vendor\Package\http\middleware\loginAuth::class,
'login.guest' => \Vendor\Package\http\middleware\loginGuest::class,
'login.permission' => \Vendor\Package\http\middleware\loginPermission::class,
The list may get longer as the package grow. How can I have better way of registering package middleware without the need to manually register all of them to $routeMiddleware
?
To add a route based middleware, do this in your package service provider (boot method).
public function boot(\Illuminate\Routing\Router $router)
{
$router->middleware('name', 'MiddlewareClass');
}
Also, for not route based middleware, class Illuminate\\Foundation\\Http\\Kernel
has these two public methods that you may call:
/**
* Add a new middleware to beginning of the stack if it does not already exist.
*
* @param string $middleware
* @return $this
*/
public function prependMiddleware($middleware)
/**
* Add a new middleware to end of the stack if it does not already exist.
*
* @param string $middleware
* @return $this
*/
public function pushMiddleware($middleware)
For laravel 5.4 and above, use:
public function boot(\Illuminate\Routing\Router $router)
{
$router->aliasMiddleware('name', 'MiddlewareClass');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.