Skip to content
Advertisement

Laravel: Not picking up __invoke method?

Trying to use invokable controllers, but it seems to fail to find the __invoke method?

Invalid route action: [AppHttpControllersAppHttpControllersMainController].

It seems to be returning true on:

if (! method_exists($action, '__invoke')) {
    throw new UnexpectedValueException("Invalid route action: [{$action}].");
}

Routes:

<?php

Route::get('/', AppHttpControllersMainController::class);

MainController:

<?php

namespace AppHttpControllers;

class MainController extends Controller
{
    public function __invoke()
    {
        dd('main');
    }
}

Advertisement

Answer

Laravel by default assumes that your controllers will be located at AppHttpControllers. So when you’re adding the full path to your controller, Laravel will check it there, at AppHttpControllersAppHttpControllersMainController.

To solve it simply remove the namespace when you’re registering the route, and register it like this:

Route::get('/', MainController::class);

Alternatively, you can stop this behavior by removing ->namespace($this->namespace) from mapWebRoutes() method on RouteServiceProvider class, which is located at AppProviders folder. Then you can register your routes like this:

Route::get('/', AppHttpControllersMainController::class);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement