Home > Software engineering >  Laravel router not found controller class
Laravel router not found controller class

Time:07-20

while creating a route, when I wanted to use a group, I stopped seeing the controller. And I have no idea what is wrong since it is in this folder and it works normally when it calls it Route::apiResource. Does anyone know what I'm doing wrong?

Route Code:

Route::group(['prefix' => 'v1', 'namespace' => 'App\Http\Controllers\Api\v1'], function(){
    Route::prefix('news')->group(function(){
        Route::get('/data?getPosts', [NewsController::class, 'index']); - Not Works
        Route::get('/data', [NewsController::class, 'index']);  - Not Works
    });
    //Route::apiResource('news', NewsController::class);  - Works
});

Error:

Target class [NewsController] does not exist.

CodePudding user response:

If you want to use the namespace prefix you can't use the "callable" syntax for the route action. You will need to use the string version, Class@method:

Route::group(['namespace' => 'App\Http\Controllers\Api\v1', ...], function () {
    Route::get(..., 'NewsController@index');
});

The callable syntax, ['Class', 'method'], expects the FQCN and overrides any namespace defined in a group (does not cascade) or so it seems; which makes sense since that is how callables work.

CodePudding user response:

The namespace option has been broken for a long time. Do not use it.

use App\Http\Controllers\Api\v1\NewsController;

Route::group(['prefix' => 'v1'], function () {
    Route::prefix('news')->group(function () {
        Route::get('/data?getPosts', [NewsController::class, 'index']);
        Route::get('/data', [NewsController::class, 'index']);
    });

    Route::apiResource('news', NewsController::class);
});
  • Related