如何在中间件Laravel中获取所请求的控制器和操作的名称

Dee*_*jay 12 php laravel laravel-5

我是Laravel的新手,我想在beforefilter middelware中获得所请求的控制器和操作的名称.

谢谢,DJ

Lim*_*nte 20

Laravel 5.6:

class_basename(Route::current()->controller);
Run Code Online (Sandbox Code Playgroud)

Laravel 5.5及更低:

您可以使用检索当前操作名称Route::currentRouteAction().不幸的是,此方法将返回完全命名空间的类名.所以你会得到类似的东西:

App\Http\Controllers\FooBarController@method
Run Code Online (Sandbox Code Playgroud)

然后只需单独的方法名称和控制器名称:

$currentAction = \Route::currentRouteAction();
list($controller, $method) = explode('@', $currentAction);
// $controller now is "App\Http\Controllers\FooBarController"

$controller = preg_replace('/.*\\\/', '', $controller);
// $controller now is "FooBarController"
Run Code Online (Sandbox Code Playgroud)


小智 6

你可以添加这个(Laravel v7及以上版本)

use Illuminate\Support\Facades\Route;
....
Route::getCurrentRoute()->getActionMethod() 
Run Code Online (Sandbox Code Playgroud)

  • `<?php echo request()->route()->getActionMethod(); ?>` 你也可以像这样使用 Helper 函数 (2认同)