user5500750
user5500750

Reputation:

Check whether Laravel Controller Action is defined

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.

Upvotes: 6

Views: 2954

Answers (1)

Sandeesh
Sandeesh

Reputation: 11906

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.

Upvotes: 10

Related Questions