I'm using Laravel 10, this code is in my web.php file
...
Route::resource('photos', PhotoController::class);
....
and it produce this list of routes:
photos ............................ photos.index › Admin\PhotoController@index
photos ............................ photos.store › Admin\PhotoController@store
photos/create ..................... photos.create › Admin\PhotoController@create
photos/{photo} .................... photos.show › Admin\PhotoController@show
photos/{photo} .................... photos.update › Admin\PhotoController@update
photos/{photo} .................... photos.destroy › Admin\PhotoController@destroy
photos/{photo}/edit ............... photos.edit › Admin\PhotoController@edit
it all works fine. Now, I want to protect with authentication all this page, and i use this code
Route::prefix('admin')->middleware('auth')->group(function () {
Route::get('photos', PhotoController::class);
});
I got this error:
Target class [PhotoController] does not exist.
so i add: ->namespace('App\Http\Controllers\Admin')
Route::prefix('admin')->namespace('App\Http\Controllers\Admin')->middleware('auth')->group(function () {
Route::resource('photos', PhotoController::class);
});
now the site works, but the command php artisan route:list says:
Class "PhotoController" does not exist
I have to specify:
use App\Http\Controllers\Admin\PhotoController;
The question is.. which is the correct way? use namespace or indicate it with ->namespace()?
The best practice is to import the namespace at the top
use App\Http\Controllers\Admin\PhotoController;
that is why Laravel shifted from the old string syntax (It's still supported but no longer best practice for Laravel team):
Route::get('/action', 'SomeController@action')
to the new syntax (supported since Larave 8):
use App\Http\Controllers\Path\SomeController;
Route::get('/action', [SomeController::class, 'action'])
Check Laravel controllers documentation examples here and here.
The benefits of this are:
->namespace('...')
chaining or using it like 'API\SomeController@...
.