Laravel 从给定 URL 获取路由名称

2022-08-30 20:32:15

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

Route::currentRouteName()

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

谢谢。


答案 1

一个非常简单的方法,Laravel 5.2

app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1'))->getName()

它输出我的路由名称,如此 slug.posts.show

更新对于POST,PUT或删除等方法,您可以这样做

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

此外,当您运行时,这将返回实例,您可以在其中调用多个有用的公共方法,例如,等等。有关更多详细信息,请查看源 https://github.com/illuminate/routing/blob/master/Route.phpapp('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST'))Illuminate\Routing\RoutegetActiongetValidators


答案 2

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

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

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

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

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


推荐