检查是否定义了 Laravel Controller Action

Check whether Laravel Controller Action is defined

我有一个应用程序,我将在数据库中存储 link,允许用户将操作分配给 link。我想避免操作不存在而出现此错误的情况;

Action App\Http\Controllers\PermissionController@index2 not defined.

所以我想检查一个动作是否存在并且有路由。如果可能的话 blade 但其他任何地方都可以。

没有任何内置方法可以执行此操作。但是我们有一个 action 辅助方法,它根据控制器操作生成路由 url。我们可以利用它并创建一个简单的辅助函数来实现相同的结果。该方法还检查给定的控制器方法是否链接到路由,因此它完全符合您的需要。

function action_exists($action) {
    try {
        action($action);
    } catch (\Exception $e) {
        return false;
    }

    return true;
}

// Sample route
Route::get('index', 'TestController@index');

$result = action_exists('TestController@index');
// $result is true

$result = action_exists('TestController@index1');
// $result is false

您也可以直接使用 class 验证操作方法是否存在,但如果方法存在但未链接到路由,这将 return 为真。