Home > OS >  Laravel using Route::controller in api
Laravel using Route::controller in api

Time:07-29

i have one controller which in that i have some functions and i want to use Route::controller, for example:

use App\Http\Controllers\Api\v1\MyController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});


Route::prefix('v1')->namespace('Api\v1')->group(function () {
    Route::controller(MyController::class)->group(function () {
        Route::get('get', 'index');
        Route::post('create', 'create');
        Route::post('update', 'update');
        Route::post('delete', 'delete');
    });
});

when i group routes with one controller i get this error:

Target class [Api\v1\App\Http\Controllers\Api\v1\MyController] does not exist.

as you can see i get multiple namespace in error result and its not correct, namespace of this controller is correct and this code work fine:

Route::prefix('v1')->namespace('Api\v1')->group(function () {
    Route::get('get', [MyController::class, 'index']);
    Route::post('create', [MyController::class, 'create']);
    Route::post('update', [MyController::class, 'update']);
    Route::post('delete', [MyController::class, 'delete']);
});

CodePudding user response:

you already have namespace in use statement so no need to use that, instead use controller groupoing.

use App\Http\Controllers\Api\v1\MyController;
...
...
Route::controller(MyController::class)->prefix('v1')->group(function () {
    Route::get('get', 'index')->name('index');
    Route::post('create', 'create')->name('create');
    Route::post('update', 'update')->name('update');
    Route::post('delete', 'delete')->name('delete');
});
  • Related