可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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();
}
}
回答1:
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();
}
}
回答2:
To get action name, you need to use:
echo Route::getCurrentRoute()->getActionName();
and not
echo Route::getActionName();
回答3:
To get only the method name you can use ...
$request->route()->getActionMethod()
or with a facade ...
Route::getActionMethod()
回答4:
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:
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 :(
回答6:
To get action name only (without controller name):
list(, $action) = explode('@', Route::getCurrentRoute()->getActionName());
回答7:
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.
回答8:
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.
回答9:
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...
回答10:
You may use to get the controller details form the request itself
$request->route()->getAction()