Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Not picking up __invoke method?

Tags:

php

laravel

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

Invalid route action: [App\Http\Controllers\App\Http\Controllers\MainController].

It seems to be returning true on:

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

Routes:

<?php

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

MainController:

<?php

namespace App\Http\Controllers;

class MainController extends Controller
{
    public function __invoke()
    {
        dd('main');
    }
}
like image 621
AAA Avatar asked Aug 14 '19 20:08

AAA


2 Answers

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);
like image 152
Ahmad H. Avatar answered Oct 18 '22 11:10

Ahmad H.


The best answer that works for everyone is laravel documentation.

just use this at the top of your route(web.php) if (websiteController is the name of your controller)

use App\Http\Controllers\WebsiteController;

and define your route like this for your index page

Route::get('/', [WebsiteController::class, 'index']);

take note of the

[             ]
like image 33
Alli Irwan Bazeet Avatar answered Oct 18 '22 12:10

Alli Irwan Bazeet