Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Target class [App\Http\Controllers\App\Http\Controllers\ApiController] does not exist

For some reason, which is probably my fault, Laravel thinks it should be looking for the class ApiController in path: 'App\Http\Controllers\App\Http\Controllers', so... it doubles, but I have no idea why.

It's a brand new Laravel 6 project, I've created the ApiController with the make:controller artisan command and added a function, like this:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ApiController extends Controller
{
    public function base() {
        return 'This is a test function';
    }
}

Then I've added a route to the api routes like this:

use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::group(['prefix' => '/v1', 'as' => 'api'], function () {
    Route::get('/base', ['uses' => ApiController::class . '@base'])->name('base');
});

As you can see, I've even 'imported' the controller, but it just can't find it. That's it, no other files or changes to the project. Also tried clearing route cache and dump-autoload, but that did not change anything.

like image 981
Serellyn Avatar asked Jan 14 '20 14:01

Serellyn


3 Answers

In my case problew was, in RouteServiceProvider, in using routes Namespace

protected $namespace = 'App\Http\Controllers';

In Laravel 8 namespace was commented out, i remove namespace from chain, because my web routes not fully moved to Laravel 8 syntax and i need this namespace.

 Route::prefix('api')
      ->middleware('api')   
      -̶>̶n̶a̶m̶e̶s̶p̶a̶c̶e̶(̶$̶t̶h̶i̶s̶-̶>̶n̶a̶m̶e̶s̶p̶a̶c̶e̶)̶
      ->group(base_path('routes/admin-api.php'));
like image 61
Oleh Avatar answered Oct 26 '22 22:10

Oleh


If you wanna ::class reference in the router, it should be done like this.

Route::group(['prefix' => '/v1', 'as' => 'api'], function () {
    Route::get('base', [ApiController::class, 'base'])->name('base');
});
like image 40
mrhn Avatar answered Oct 27 '22 00:10

mrhn


This should work:

Route::group(['prefix' => '/v1', 'as' => 'api'], function () {
    Route::get('base', 'ApiController@base')->name('base');
});

No need to add the "use", since controllers are referenced from the App/Controllers namespace, as you can corroborate on the RouteServiceProvider.

like image 32
JoeGalind Avatar answered Oct 26 '22 23:10

JoeGalind