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

2022-01-02 00:00:00 routing php laravel

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

In Laravel, we can get route name from current URL via this:

Route::currentRouteName()

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

But, how can we get the route name from a specific given URL?

谢谢.

推荐答案

一个非常简单的方法Laravel 5.2

A very easy way to do it Laravel 5.2

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

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

It outputs my Route name like this slug.posts.show

更新:对于像POST、PUT或DELETE这样的方法,你可以这样做

Update: For method like POST, PUT or DELETE you can do like this

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

同样,当你运行 app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST')) 这将返回 IlluminateRoutingRoute 实例,您可以在其中调用多个有用的公共方法,例如 getActiongetValidators等检查源https://github.com/illuminate/routing/blob/master/Route.php 了解更多详情.

Also when you run app('router')->getRoutes()->match(app('request')->create('/qqq/posts/68/u1', 'POST')) this will return IlluminateRoutingRoute instance where you can call multiple useful public methods like getAction, getValidators etc. Check the source https://github.com/illuminate/routing/blob/master/Route.php for more details.

相关文章