Can I use same controller name 2 or more times in laravel?

2.4k views Asked by At

I have same controller name(suppose Login.php) in 2 different folders in laravel 8 project. In route it is showing error if I use them in following way.

use App\Http\Controllers\my_controller1\Login;
use App\Http\Controllers\my_controller2\Login;

Error Looks Like

Symfony\Component\ErrorHandler\Error\FatalError

Cannot use App\Http\Controllers\my_controller2\Login as Login because the name is already in use

It will not show error If I use in following way:

use App\Http\Controllers\my_controller1\Login;

and

Route::get('/loginA',[App\Http\Controllers\my_controller2\Login::class,'abc']);

Route::get('/loginB',[Login::class,'abc']);

NOTE: Folder and Controller names are just for assumption.

2

There are 2 answers

2
ceejayoz On BEST ANSWER

There is 2 different use statements. use App\Http\Controllers\my_controller1\Login; and use App\Http\Controllers\my_controller2\Login;

You'll want to alias one of these if you're using them both in the same file.

use App\Http\Controllers\my_controller2\Login as Login2;
2
theovier On

You could give them different names by importing them like this

use App\Http\Controllers\my_controller1\Login as Login1;
use App\Http\Controllers\my_controller2\Login as Login2;

However, there should not be the need to have two controllers with the same name as it suggests that they are responsible for the same thing and probably could be merged.

Also, your naming seems a bit off; consider using camelCase for folder names (e.g. \customControllers\ instead of \my_controller1\) and naming controllers LoginController instead of Login only (see naming conventions for Laravel).