How to Get Current Route Name?

2019-01-05 08:47发布

In Laravel 4 I was able to get the current route name using...

Route::currentRouteName()

How can I do it in Laravel 5?

18条回答
Ridiculous、
2楼-- · 2019-01-05 09:16

Now in Laravel 5.3 I am seeing that can be made similarly you tried:

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

https://laravel.com/docs/5.3/routing#accessing-the-current-route

查看更多
孤傲高冷的网名
3楼-- · 2019-01-05 09:16

Accessing The Current Route

Get current route name in Blade templates

{{ Route::currentRouteName() }} to get the name of route

for more info https://laravel.com/docs/5.5/routing#accessing-the-current-route

查看更多
闹够了就滚
4楼-- · 2019-01-05 09:17

Looking at \Illuminate\Routing\Router.php you can use the method currentRouteNamed() by injecting a Router in your controller method. For example:

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

or using the Route facade:

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

You could also use the method is() to check if the route is named any of the given parameters, but beware this method uses preg_match() and I've experienced it to cause strange behaviour with dotted route names (like 'foo.bar.done'). There is also the matter of performance around preg_match() which is a big subject in the PHP community.

public function index(Request $request) {
    return view(\Route::is('foo', 'bar') ? 'view1' : 'view2');
}
查看更多
狗以群分
5楼-- · 2019-01-05 09:18

Accessing The Current Route(v5.3 onwards)

You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request:

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

Refer to the API documentation for both the underlying class of the Route facade and Route instance to review all accessible methods.

Reference : https://laravel.com/docs/5.2/routing#accessing-the-current-route

查看更多
放我归山
6楼-- · 2019-01-05 09:23

I have used for getting route name in larvel 5.3

Request::path()

查看更多
可以哭但决不认输i
7楼-- · 2019-01-05 09:27

If you need url, not route name, you do not need to use/require any other classes:

url()->current();
查看更多
登录 后发表回答