问题
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