Laravel从给定的URL获取路由名称

use*_*781 14 php routing laravel

在Laravel中,我们可以通过以下方式从当前URL获取路径名称:

Route::currentRouteName()
Run Code Online (Sandbox Code Playgroud)

但是,我们如何从特定的给定URL获取路由名称?

谢谢.

ARI*_*ANA 27

一个非常简单的方法 Laravel 5.2

app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1'))->getName()
Run Code Online (Sandbox Code Playgroud)

它像这样输出我的路线名称 slug.posts.show

更新:对于像POST,PUTDELETE这样的方法,你可以这样做

app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST'))->getName()//reference https://github.com/symfony/http-foundation/blob/master/Request.php#L309
Run Code Online (Sandbox Code Playgroud)

此外,当你运行app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST'))它将返回Illuminate\Routing\Route实例,你可以调用多个有用的公共方法,如getAction,getValidators等.检查源https://github.com/illuminate/routing/blob/master/Route.php获取更多详细信息.


Bas*_*MHL 11

上述解决方案都不适合我。

这是将路由与 URI 匹配的正确方法:

$url = 'url-to-match/some-parameter';

$route = collect(\Route::getRoutes())->first(function($route) use($url){
   return $route->matches(request()->create($url));
});
Run Code Online (Sandbox Code Playgroud)

其他解决方案执行与容器的绑定,并且可能会搞砸您的路线......


Seb*_*rre 5

我认为开箱即用的 Laravel 无法做到这一点。另请记住,Laravel 中并非所有路由都已命名,因此您可能想要检索路由对象,而不是路由名称。

一种可能的解决方案是扩展默认\Iluminate\Routing\Router类并向使用受保护方法的自定义类添加公共方法Router::findRoute(Request $request)

一个简化的例子:

class MyRouter extends \Illuminate\Routing\Router {

    public function resolveRouteFromUrl($url) {
        return $this->findRoute(\Illuminate\Http\Request::create($url));
    }
}
Run Code Online (Sandbox Code Playgroud)

应该返回与您指定的 URL 匹配的路由,但我还没有实际测试过这一点。

请注意,如果您希望这个新的自定义路由器替换内置路由器,您可能还需要创建一个新的 ServiceProvider 以将新类注册到 IoC 容器中,而不是默认的类。

您可以根据您的需要调整以下代码中的 ServiceProvider:

https://github.com/jasonlewis/enhanced-router

否则,如果您只想根据需要在代码中手动实例化自定义路由器,则必须执行以下操作:

$myRouter = new MyRouter(new \Illuminate\Events\Dispatcher());
$route = $myRouter->resolveRouteFromUrl('/your/url/here');
Run Code Online (Sandbox Code Playgroud)


小智 5

无需扩展默认类即可完成此操作\Iluminate\Routing\Router

    Route::dispatchToRoute(Request::create('/your/url/here'));
    $route = Route::currentRouteName();
Run Code Online (Sandbox Code Playgroud)

如果Route::currentRouteName()多次dispatchToRoute调用,它将返回当前发送请求的路由名称。