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:47

To get the route action name on Middleware i do that:

<?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);
    }
}

EDIT: You will don't get the routes which are protected by this middleware :(

查看更多
趁早两清
3楼-- · 2019-01-18 21:47

You may use to get the controller details form the request itself

$request->route()->getAction()
查看更多
地球回转人心会变
4楼-- · 2019-01-18 21:49

Instead

use Illuminate\Routing\Route;

Use this

use Illuminate\Support\Facades\Route;

If you want to get the alias of the route, you can use:

Route::getCurrentRoute()->getName()
查看更多
女痞
5楼-- · 2019-01-18 21:52

In Laravel 5.5 if you just want the method/action name i.e. show, edit, custom-method etc... do this

Route::getCurrentRoute()->getActionMethod() 

No need to use explode or list to get the actual method to be called. Thanks to Laravel who thought of this.

查看更多
登录 后发表回答