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条回答
手持菜刀,她持情操
2楼-- · 2019-01-05 09:35

In a controller action, you could just do:

public function someAction(Request $request)
{
    $routeName = $request->route()->getName();
}

$request here is resolved by Laravel's service container.

getName() returns the route name for named routes only, null otherwise (but you could still explore the \Illuminate\Routing\Route object for something else of interest).

In other words, you should have your route defined like this to have "nameOfMyRoute" returned:

Route::get('my/some-action', [
    'as' => 'nameOfMyRoute',
    'uses' => 'MyController@someAction'
]);
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-05 09:36

In 5.2, you can use the request directly with:

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

or via the helper method:

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

Output example:

"home.index"
查看更多
别忘想泡老子
4楼-- · 2019-01-05 09:37

If you want to select menu on multiple routes you may do like this:

<li class="{{ (Request::is('products/*') || Request::is('products') || Request::is('product/*') ? 'active' : '') }}"><a href="{{url('products')}}"><i class="fa fa-code-fork"></i>&nbsp; Products</a></li>

Or if you want to select just single menu you may simply do like this:

<li class="{{ (Request::is('/users') ? 'active' : '') }}"><a href="{{url('/')}}"><i class="fa fa-envelope"></i>&nbsp; Users</a></li>

Also tested in Laravel 5.2

Hope this help someone.

查看更多
混吃等死
5楼-- · 2019-01-05 09:37

Laravel 5.2 You can use

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

It will give you current route name.

查看更多
聊天终结者
6楼-- · 2019-01-05 09:41

Shortest way is Route facade \Route::current()->getName()

This also works in laravel 5.4.*

查看更多
We Are One
7楼-- · 2019-01-05 09:42

Found a way to find the current route name works for laravel v5 , v5.1.28 and v5.2.10

Namespace

use Illuminate\Support\Facades\Route;

and

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

For Laravel laravel v5.3 you can just use:

use Illuminate\Support\Facades\Route;

Route::currentRouteName();
查看更多
登录 后发表回答