如何在Laravel的中间件中获取Route [英] How to get Route in Middleware in Laravel
问题描述
目前,我可以通过将其注入要使用的方法中来获得控制器中的路由.
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);
}
}
遇到错误.
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.
推荐答案
删除构造函数/将其设置为默认值;
Remove your constructor/put it to default like;
public function __construct(){}
尝试通过handle方法访问路由;
Try accessing the route via the handle method like so;
$request->route();
因此,您应该能够像这样访问动作名称;
So you should be able to access the action name like so;
$request->route()->getActionName();
如果路线返回为空,请确保已在App/Http/Kernel.php中注册了中间件,就像这样;
If the route return is null be sure you have registered the middleware within the App/Http/Kernel.php, like so;
protected $middleware = [
...
'Path\To\Middleware',
];
以上内容适用于全球中间件
对于特定于路由的过滤,将'Path\To\Middleware',
放在App\Providers
文件夹内RouteServiceProvider.php的中间件数组中.
For route specific filtering place the 'Path\To\Middleware',
within the middleware array within RouteServiceProvider.php within the App\Providers
folder.
您还可以通过app()->router->getCurrentRoute()
访问路线对象.
You can also access the route object via app()->router->getCurrentRoute()
.
您可以尝试以下方法;
You could possibly try the following;
$route = Route::getRoutes()->match($request);
$route->getActionName();
这将从RouteCollection
获取路线.确保将其封装在try catch中,因为这会抛出NotFoundHttpException
.
This get the route from the RouteCollection
. Be sure to encapsulate this within a try catch as this will throw a NotFoundHttpException
.
这篇关于如何在Laravel的中间件中获取Route的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!