目前,我可以通过将路由注入到我想使用它的方法中来获取控制器中的路由。
<?php namespace App'Http'Controllers;
use Illuminate'Routing'Route;
class HomeController extends Controller
{
public function getIndex(Route $route)
{
echo $route->getActionName();
}
}
但是,我正在尝试在中间件中执行类似操作,但无法使其运行。
<?php namespace App'Http'Middleware;
use Closure;
use Illuminate'Routing'Route;
use Illuminate'Contracts'Routing'Middleware;
class SetView implements Middleware {
protected $route;
public function __construct(Route $route)
{
$this->route = $route;
}
public function handle($request, Closure $next)
{
echo $this->route->getActionName();
return $next($request);
}
}
收到错误。
Unresolvable dependency resolving [Parameter #0 [ <required> $methods ]] in class Illuminate'Routing'Route
不太确定该怎么办。真的不在乎它是否是路由,但需要以某种方式获取该操作名称。
删除你的构造函数/将其设置为默认值,例如;
public function __construct(){}
尝试通过 handle 方法访问路由,如下所示;
$request->route();
因此,您应该能够像这样访问操作名称;
$request->route()->getActionName();
如果路由返回为 null,请确保您已在 App/Http/Kernel.php 中注册了中间件,如下所示;
protected $middleware = [
...
'Path'To'Middleware',
];
以上是针对全局中间件的
对于特定于路由的过滤,请将'Path'To'Middleware',
放在 RouteServiceProvider 的中间件数组中.php放在 App'Providers
文件夹中。
您还可以通过 app()->router->getCurrentRoute()
访问路由对象。
编辑:
您可以尝试以下方法;
$route = Route::getRoutes()->match($request);
$route->getActionName();
这将从RouteCollection
获取路线。请务必将其封装在 try catch 中,因为这会引发NotFoundHttpException
。
对于 Laravel 5.1.x
在您的全局中间件中
use Illuminate'Support'Facades'Route;
$route = Route::getRoutes()->match($request);
$currentroute = $route->getName();