Home > Back-end >  Laravel namespaced controllers already in use
Laravel namespaced controllers already in use

Time:10-17

I have my .api routes and have namespaced my versions v1,v2, I have run composer dump-autoload.

use App\Http\Controllers\Api\V1\ProductController;
use App\Http\Controllers\Api\V2\ProductController;

Prefix

Route::group(['prefix' => 'v2', 'namespace' => 'App\Http\Controllers\Api\V2'], function(){
    Route::get('products', [ProductController::class, 'index']);
    Route::get('products/{product-type}', [ProductController::class, 'index']);
    Route::get('products/{product-type}/{product-sub-type}', [ProductController::class, 'subType']);
    Route::get('products/{product-type}/{product-sub-type}/{id}', [ServerController::class, 'show']);
});

Why do I get an error Cannot use App\Http\Controllers\Api\V2\ProductController as ProductController because the name is already in use even though I've namespaced them?

CodePudding user response:

use App\Http\Controllers\Api\V1\ProductController;
use App\Http\Controllers\Api\V2\ProductController as V2ProductController;

=> same controller name is not used.have to give another name using "as" that name used in Route

Route::group(['prefix' => 'v2', 'namespace' => 'App\Http\Controllers\Api\V2'], function(){
    Route::get('products', [V2ProductController::class, 'index']);
    Route::get('products/{product-type}', [V2ProductController::class, 'index']);
    Route::get('products/{product-type}/{product-sub-type}', [V2ProductController::class, 'subType']);
    Route::get('products/{product-type}/{product-sub-type}/{id}', [V2ProductController::class, 'show']);
});
  • Related