Laravel 5 how to get route action name?

2019-01-18 21:34发布

I'm trying to get the current route action, but I'm not sure how to go about it. In Laravel 4 I was using Route::currentRouteAction() but now it's a bit different.

I'm trying to do Route::getActionName() in my controller but it keeps giving me method not found.

<?php namespace App\Http\Controllers;

use Route;

class HomeController extends Controller
{
    public function getIndex()
    {
        echo 'getIndex';
        echo Route::getActionName();
    }
}

10条回答
劳资没心,怎么记你
2楼-- · 2019-01-18 21:34

For Laravel 5.1 use:

$route = new Illuminate\Routing\Route();
$route->getActionName(); // Returns App\Http\Controllers\MyController@myAction
$route->getAction(); // Array with full controller info

There are lots of useful methods in this class. Just check the code for more details.

查看更多
萌系小妹纸
3楼-- · 2019-01-18 21:39

To get only action name in Laravel 5.4

explode('@', Route::getCurrentRoute()->getActionName())[1]

Can't find any better way, to use in view, in one line...

查看更多
Lonely孤独者°
4楼-- · 2019-01-18 21:40

In Laravel 5 you should be using Method or Constructor injection. This will do what you want:

<?php namespace App\Http\Controllers;

use Illuminate\Routing\Route;

class HomeController extends Controller
{
    public function getIndex(Route $route)
    {
        echo 'getIndex';
        echo $route->getActionName();
    }
}
查看更多
戒情不戒烟
5楼-- · 2019-01-18 21:43

To get action name, you need to use:

echo Route::getCurrentRoute()->getActionName();

and not

echo Route::getActionName();
查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-18 21:44

To get only the method name you can use ...

$request->route()->getActionMethod()

or with a facade ...

Route::getActionMethod()
查看更多
欢心
7楼-- · 2019-01-18 21:46

To get action name only (without controller name):

list(, $action) = explode('@', Route::getCurrentRoute()->getActionName());
查看更多
登录 后发表回答