在Laravel v4中,我可以使用…

Route::currentRouteName()

我如何在Laravel v5和Laravel v6中做到这一点?


当前回答

访问当前路由

在Blade模板中获取当前路由名

{{ Route::currentRouteName() }}

更多信息https://laravel.com/docs/5.5/routing#accessing-the-current-route

其他回答

查看\Illuminate\Routing\Router.php,您可以通过在控制器方法中注入路由器来使用方法currentRouteNamed()。例如:

use Illuminate\Routing\Router;
public function index(Request $request, Router $router) {
   return view($router->currentRouteNamed('foo') ? 'view1' : 'view2');
}

或者使用Route facade:

public function index(Request $request) {
   return view(\Route::currentRouteNamed('foo') ? 'view1' : 'view2');
}

你也可以使用is()方法来检查路由是否被命名为任何给定的参数,但要注意这个方法使用preg_match(),我曾经经历过它导致使用虚线路由名的奇怪行为(如'foo.bar.done')。还有preg_match()的性能问题 这是PHP社区的一个大主题。

public function index(Request $request) {
    return view(\Route::is('foo', 'bar') ? 'view1' : 'view2');
}

Laravel 5.2可以使用

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

它会给你当前的路由名。

有很多方法可以做到这一点。你可以输入:

\Illuminate\Support\Facades\Request::route()->getName()

获取路由名称。

在控制器中访问当前路由名

Ie - http://localhost/your_project_name/edit

$request->segment(1);  // edit

(或)

$request->url();  // http://localhost/your_project_name/edit

找到了一种查找当前路由名称的方法,适用于laravel v5, v5.1.28和v5.2.10

名称空间

use Illuminate\Support\Facades\Route;

and

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

对于Laravel Laravel v5.3,你可以使用:

use Illuminate\Support\Facades\Route;

Route::currentRouteName();