如何在流明框架中获取中间件上的当前路由?

问题描述 投票:2回答:8

我已经使用流明开发了API应用程序。并进行访问权限控制。我想在中间件中获取当前路由。但是,我总是在以下方面得到空值:

   $route = $request->route();

我已经在使用routeMiddleware和分派器的Can I get current route information in middleware with Lumen?上进行了尝试。但是它仍然返回null。如何在中间件上获取当前路由?

非常感谢..

php laravel permissions middleware lumen
8个回答
2
投票
maybe this

$request   = new \Illuminate\Http\Request;
$method    = $request->getMethod();
$pathInfo  = app()->getPathInfo();
$routeName = app()->getRoutes()[$method.$pathInfo]['action']['as'];

2
投票

请更新您的流明...一切正常,没有问题

namespace App\Http\Middleware;

public function handle($request, Closure $next)
{
    $route = $request->route();
    $path = $request->getPathInfo();

    // your code here
    return $next($request);
}

1
投票

有一种更优雅的方法。

如果尚未扩展Application类,请添加此额外方法:

use Laravel\Lumen\Application;

class YourApplication extends Application
{
    /** override other methods if needed */

    /**
     * @return string
     */
    public function getCurrentRoute()
    {
        return $this->currentRoute;
    }

}

然后您可以像这样在中间件中访问它:

$route = app()->getCurrentRoute();
$action = $route[1];
$info = $action['uses']; // string(57) "YourApp\Http\Controller\Public\UserController@view"

0
投票
Route::currentRouteName();

将返回您的路线名称;


0
投票

不幸的是,这不可能。至少它不像调用getCurrentRoute()那样简单。

您需要进行路由收集,然后再次将其与请求路径匹配。

看这个简单的例子:https://gist.github.com/radmen/92200c62b633320b98a8

[请注意,这段代码的某些部分可能无法正常工作;)我从我的应用程序中提取了这段代码(稍有不同的用例),并尝试使其适合您的情况。


0
投票

在全局中间件中,您不能直接从请求中获取路由,但是如果在routeMiddleware中则可以获取。

所以,只需使用routeMiddleware,在中间件中使用$request->route()

如果只想在全局中间件中获取它,只需克隆$ request并设置一个调度程序即可


0
投票

实际上不是。流明正在使用完全不同的路由器,而不是本地的laravel路由器。所以不一样。尽管流明是基于laravel的,但有些(或者我应该说引擎的近60%是不同的。包括使用Nikic / fastroute的路由器应用程序。...


-1
投票

来自Laravel文档:

http://laravel.com/docs/5.1/requests#basic-request-information

path方法返回请求的URI。因此,如果传入请求的目标是http://domain.com/foo/bar,则path方法将返回foo / bar:

$uri = $request->path();

甚至还有其他方法可能会有所帮助:

if ($request->is('admin/*')) {
    // do something
}
© www.soinside.com 2019 - 2024. All rights reserved.