21

我正在尝试获取当前的路线操作,但我不确定如何去做。在我使用的 Laravel 4 中,Route::currentRouteAction()但现在有点不同了。

我试图Route::getActionName()在我的控制器中做,但它一直给我找不到方法。

<?php namespace App\Http\Controllers;

use Route;

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

13 回答 13

25

要获取操作名称,您需要使用:

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

并不是

echo Route::getActionName();
于 2014-11-10T09:50:05.493 回答
22

在 Laravel 5 中,您应该使用方法或构造函数注入。这将做你想要的:

<?php namespace App\Http\Controllers;

use Illuminate\Routing\Route;

class HomeController extends Controller
{
    public function getIndex(Route $route)
    {
        echo 'getIndex';
        echo $route->getActionName();
    }
}
于 2014-11-10T10:45:27.253 回答
10

要仅获取您可以使用的方法名称...

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

或带有门面...

Route::getActionMethod()
于 2017-05-10T13:55:48.933 回答
6

仅获取操作名称(没有控制器名称):

list(, $action) = explode('@', Route::getCurrentRoute()->getActionName());
于 2015-11-10T15:55:23.440 回答
4

反而

use Illuminate\Routing\Route;

用这个

use Illuminate\Support\Facades\Route;

如果要获取路由的别名,可以使用:

Route::getCurrentRoute()->getName()
于 2015-04-20T21:13:58.460 回答
3

要在中间件上获取路由操作名称,我这样做:

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Router;

class HasAccess {

    protected $router;

    public function __construct(User $user, Router $router)
    {
        $this->router = $router;
    }

    public function handle($request, Closure $next)
    {
        $action_name = $this->router->getRoutes()->match($request)->getActionName();
        //$action_name will have as value 'App\Http\Controllers\HomeController@showWelcome'
        //Now you can do what you want whit the action name 
        return $next($request);
    }
}

编辑:您将不会获得受此中间件保护的路由:(

于 2015-09-30T08:39:33.360 回答
2

在 Laravel 5.4 中仅获取操作名称

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

找不到更好的方法,在视图中使用,在一行中......

于 2017-06-19T09:34:26.457 回答
2

在 Laravel 5.5 中,如果您只想要方法/动作名称,即显示、编辑、自定义方法等......请执行此操作

Route::getCurrentRoute()->getActionMethod() 

无需使用explode 或list 来获取要调用的实际方法。感谢 Laravel 想到这一点。

于 2018-01-08T16:52:27.013 回答
1

对于 Laravel 5.1 使用:

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

这个类中有很多有用的方法。只需检查代码以获取更多详细信息。

于 2015-08-24T20:44:30.660 回答
1

您可以使用从请求本身获取控制器详细信息

$request->route()->getAction()
于 2017-07-05T07:45:49.223 回答
1

这对我来说非常好。

$request->route()->getActionMethod()
于 2020-01-13T11:11:53.597 回答
0

我用过这个,它在视图中工作。

几个选项。

将变量从控制器传递给视图。设置全局视图变量使用视图作曲家。您需要根据您的用例选择其中之一。

Route::getCurrentRoute()->getAction();
Route::currentRouteAction();
Route::currentRouteName();
于 2020-01-14T02:44:35.370 回答
0
$request->route()->getAction()['prefix'] // return 'api'
于 2019-09-03T22:31:47.873 回答