Check whether Laravel Controller Action is defined

*爱你&永不变心* 提交于 2019-12-23 10:38:44

问题


I have an application where I will be storing links in the database allowing the user to assign actions to the link. I want to avoid the situation where the action does not exist and I get this error;

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

So I would like to check whether an action exists and has route. If possible in blade but anywhere else is fine.


回答1:


There isn't any built in way to do this. But we have a action helper method which generates route url based on the controller action. We can make use of this and create a simple helper function to achieve the same result. The method also checks if the given controller method is linked to a route, so it does exactly what you need.

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

You could also verify the existence of the action method using the class directly, but this would return true if the method exists but isn't linked to a route.



来源:https://stackoverflow.com/questions/44344834/check-whether-laravel-controller-action-is-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!