Laravel: Not picking up __invoke method?

Laravel by default assumes that your controllers will be located at App\Http\Controllers\. So when you're adding the full path to your controller, Laravel will check it there, at App\Http\Controllers\App\Http\Controllers\MainController.

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 App\Providers folder. Then you can register your routes like this:

Route::get('/', \App\Http\Controllers\MainController::class);

Alternatively, you can use:

Route::get('/', [\App\Http\Controllers\MainController::class, '__invoke']);

In this case, the namespace provided in RouteServiceProvider won't be taken into account. The advantage of this is that now your IDE will be able to reference the class usage and you can navigate by clicking on it.

Tags:

Php

Laravel