【PHP】laravel中获取当前路由名称

$name = Route::currentRouteName(); 这句话的使用需要引入什么类吗?该引入哪个类?
求详细过程

结论:Route类是必须引入的。所以可以调用静态方法 currentRouteName()。

1 - 为什么不引入Route类也可以运行?

因为Route类是在系统启动时作为全局类进行了注册。

在文件 config/app.php 文件内如下所示:

Route门面此处注册到全局,也就是根命名空间。所以在程序内,直接使用 Route::method() 不会有任何问题。

我们在编程中,对于全局注册的类,也需要通过此方法,添加注册。

2 - 获取当前路由名称的一些方法举例

使用Route类的方法:

Route::getCurrentRoute()->getPath();

或者使用Request类的方法:

\Request::route()->getName();

laravel 5.1 你得这么写:

use Illuminate\Support\Facades\Route;

$currentPath= Route::getFacadeRoot()->current()->uri();

到了5.2版本,就是题主的写法:

Route::currentRouteName();

5.3版本到5.8版本,更加灵活了:

$uri = $request->path();

使用 Request 对象的方法就可以返回。获取路由,路由名称,方法名:

    $route = Route::current();

    $name = Route::currentRouteName();

    $action = Route::currentRouteAction();


到了laravel 7.x 对请求对象 Request 有了更加丰富的特性:

$request->route()->getName();


结语

以上获取路由名的方法,根据不同laravel版本,进行不同的处理。

细节上的不同一定要多加注意。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-01-30

不需要特别加载吧。你可以直接看看这个方法是怎么调用的在

#laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php
#大概Line-1585

/**
 * Get the current route name.
 *
 * @return string|null
 */
public function currentRouteName()
{
return ($this->current()) ? $this->current()->getName() : null;
}

追问

我添加$name = Route::currentRouteName();
然后运行这个页面会直接报致命错误,说route not found,.............

追答

你在哪里调用这个方法?你确定Route自动加载了吗?

本回答被提问者和网友采纳
第2个回答  2016-02-03
用到了Route相关的Facade,所以引用illuminate\support\facades\route
第3个回答  2018-01-30
$request->getRequestUri();
相似回答