13

目前我可以通过将路由注入到我想要使用它的方法中来获取控制器中的路由。

<?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

不知道该怎么办。真的不在乎它是否是一条路线,但需要以某种方式获取该动作名称。

4

2 回答 2

27

删除您的构造函数/将其设置为默认值;

public function __construct(){}

尝试像这样通过句柄方法访问路由;

 $request->route();

所以你应该能够像这样访问动作名称;

 $request->route()->getActionName();

如果路由返回为空,请确保您已在 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.

于 2014-11-12T13:05:56.690 回答
11

对于 Laravel 5.1.x

在您的全局中间件中

use Illuminate\Support\Facades\Route;

$route = Route::getRoutes()->match($request);
$currentroute = $route->getName();
于 2017-03-15T18:21:52.927 回答