Laravel not recognizing Controller __invoke()

Viewed 5454

Can't debug this simple routing issue, despite going through several similar posts.

TestController is not invokable. The controller class TestController is not invokable. Did you forget to add the __invoke method or is the controller's method missing in your routes file?

I have played around with it as many permutations as I can find on Stack and nothing changes it. I have confirmed that simple routing, ie:

Route::get('/', function () {
    return view('welcome');
});

works, but I can't get the controllers to work. I have cleared the cache and uncommented the $namespace, nothing makes a difference. In fact, the error message doesn't seem to change, which leads me to believe it's not the routing but something to do with the Controllers. But I am a newb and am not seeing it.

from web.php:

Route::get('/test', TestController::class);

TestController.php:

<?php

namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    
    class TestController extends Controller {
        public function __invoke() {
            return view('welcome');
        }
    }
3 Answers

This normally happens when you do not have the use statement for the FQCN of the controller.

In the routes file where you are declaring the route ensure that the use statement for the Controller namespace is added. Especially since Laravel 8.x the default namespace for controllers is not set to App\Http\Controllers unlike the earlier versions.

//routes file
use App\Http\Controllers\TestController;

Route::get('/test', TestController::class);

Just as a side note if you are using an invokable controller class to return just a view, you can use the Route::view() method instead

//Assuming that you have a resources/views/test.blade.php 
Route::view('/test', 'test');

Maybe this helps someone similar to me, who overlooks a simple problem: I wrote:

Route::post('controller/{resource}/action', \App\Http\Controllers\MyController::class, 'action')->name('controller.action');

Instead what I needed was:

Route::post('controller/{resource}/action', [\App\Http\Controllers\MyController::class, 'action'])->name('controller.action');

So basically I was missing the [] around the controller class and action params, they go together in an array - got to remember that. :)

Sorry if it is a just a tiny bit off-topic, but I searched for my problem and ended up here, therefore this just might help someone else too.

I don't know if you still need to hear this but change your

Route::get('/test', TestController::class); into Route::get('/test', [TestController::class, @MethodName]);

Also, call your model into the Controller.file use App\Models\Test;

Related