如何在 Laravel 的中间件中获取路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26887666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Route in Middleware in Laravel
提问by Rob
Currently I can get a route in a controller by injecting it into the method I want to use it in.
目前,我可以通过将路由注入到我想在其中使用的方法中来获取控制器中的路由。
<?php namespace App\Http\Controllers;
use Illuminate\Routing\Route;
class HomeController extends Controller
{
public function getIndex(Route $route)
{
echo $route->getActionName();
}
}
However I'm trying to perform something similar in middleware but can't get it going.
但是,我正在尝试在中间件中执行类似的操作,但无法实现。
<?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);
}
}
Getting an error.
得到一个错误。
Unresolvable dependency resolving [Parameter #0 [ <required> $methods ]] in class Illuminate\Routing\Route
Not really sure what to do with that. Don't really care if it's a route or not, but need to get that action name somehow.
不太确定该怎么办。并不真正关心它是否是路线,但需要以某种方式获得该动作名称。
回答by Matt Burrow
Remove your constructor/put it to default like;
删除您的构造函数/将其设置为默认值;
public function __construct(){}
Try accessing the route via the handle method like so;
尝试像这样通过 handle 方法访问路由;
$request->route();
So you should be able to access the action name like so;
所以你应该能够像这样访问动作名称;
$request->route()->getActionName();
If the route return is null be sure you have registered the middleware within the App/Http/Kernel.php, like so;
如果路由返回为空,请确保您已在 App/Http/Kernel.php 中注册了中间件,如下所示;
protected $middleware = [
...
'Path\To\Middleware',
];
The above is for global middleware
以上是针对全局中间件
For route specific filtering place the 'Path\To\Middleware',within the middleware array within RouteServiceProvider.php within the App\Providersfolder.
对于特定于路由的过滤,将'Path\To\Middleware',RouteServiceProvider.php 中的中间件数组放置在App\Providers文件夹内。
You can also access the route object via app()->router->getCurrentRoute().
您还可以通过访问路由对象app()->router->getCurrentRoute()。
Edit:
编辑:
You could possibly try the following;
您可以尝试以下操作;
$route = Route::getRoutes()->match($request);
$route->getActionName();
This get the route from the RouteCollection. Be sure to encapsulate this within a try catch as this will throw a NotFoundHttpException.
这从RouteCollection. 请务必将其封装在 try catch 中,因为这将抛出一个NotFoundHttpException.
回答by xnohat
For Laravel 5.1.x
对于 Laravel 5.1.x
In your global middleware
在您的全球中间件中
use Illuminate\Support\Facades\Route;
$route = Route::getRoutes()->match($request);
$currentroute = $route->getName();

