从Laravel 5中的中间件获取当前路线动作名称 [英] Get current route action name from middleware in laravel 5
问题描述
我有这样的中间件:
<?php
namespace App\Http\Middleware;
use App\Contracts\PermissionsHandlerInterface;
use Closure;
class PermissionsHanlderMiddleware {
public $permissionsHandler;
function __construct(PermissionsHandlerInterface $permissionsHandler) {
$this -> permissionsHandler = $permissionsHandler;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
$routeAction = $request->route()->getActionName();
/*
do some operations
*/
return $next($request);
}
}
但是$request->route()
总是返回null
,我认为是这样,因为尚未随请求一起分派路由器.
but $request->route()
always returns null
, I think its because the router hasn't been dispatched with the request.
注意:我将中间件添加到Kernal.php
全局中间件中,以便在每次请求之前运行,如下所示:
Note: I added my middleware to Kernal.php
global middlewares to run before each request as the following
protected $middleware = [
.
.
.
'App\Http\Middleware\PermissionsHanlderMiddleware',
];
我想在执行$next($request)
之前获取路由操作名称,以执行一些权限操作.我该怎么办?
I want to get route action name before the execution of $next($request)
to do some permission operations. How can i do this ?
推荐答案
如果尚未调度路由器,则无法获取路由操作名称.路由器类尚未完成其工作-因此您无法执行$router->request()
-它只会为空.
You cannot get the route action name if the router has not yet been dispatched. The router class has not yet done its stuff - so you cannot do $router->request()
- it will just be null.
如果它与$routeMiddleware
一样作为routeMiddleware运行-那么您可以执行$router->request()
If it runs as routeMiddleware as $routeMiddleware
- then you can just do $router->request()
您可以在路由器运行之前在中间件中获取URI字符串-如果愿意,可以在其中执行一些逻辑:$request->segments()
.即通过这种方式,您可以查看URI段是否匹配特定的路由并运行一些代码.
You can get the URI string in the middleware before the router has run - and do some logic there if you like: $request->segments()
. i.e. that way you can see if the URI segment matches a specific route and run some code.
我可以快速想到的一种方法就是将您的所有路线包装成这样的组:
One way I can quickly think of is just wrap all your routes in a group like this:
$router->group(['middleware' => 'permissionsHandler'], function() use ($router) {
// Have every single route here
});
这篇关于从Laravel 5中的中间件获取当前路线动作名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!