If your application gets bigger, it makes sense to structure Controllers with sub-folders. But it takes a little more effort than just moving the files here and there. Let me explain the structure.
For example, we want to have a sub-folder app/Http/Controllers/Admin and then inside of it we have our AdminController.php, that’s fine. What we need to do inside of the file itself:
1. Correct namespace – specify the inner folder:
namespace App\Http\Controllers\Admin;
2. Use Controller – from your inner-namespace Laravel won’t “understand” extends Controller, so you need to add this:
use App\Http\Controllers\Controller;
3. Routes – specify full path
This wouldn’t work anymore:
Route::get('admin', 'AdminController@getHome');
This is the correct way:
Route::get('admin', 'Admin\AdminController@getHome');
And that’s it – now you can use your controller from sub-folder.
Hi,
Nice tip. Also you can add separate routing file and register it with service provider in your desired namespace, same as standard routing file is registered.
Edvinas, yes, agree, but that would apply more to separate packages – then it makes sense to have separate service providers. Otherwise it’s an overkill imho.
You don’t have to create new one, just use existing one.
If you have more than a couple controllers in a subfolder, you can use a route group with these controllers’ namespace to keep your routes nicely organized:
Route::group([‘namespace’ => ‘Admin’], function() {
Route::get(‘admin’, ‘AdminController@getHome’);
….
});
Or with a prefix and middleware:
Route::group([‘prefix’ => ‘admin’, ‘middleware’ => ‘auth’, ‘namespace’ => ‘Admin’], function() {
Route::get(‘/’, ‘AdminController@getHome’);
….
});
Great point, Ethet. Thanks for comment.
Hi,
Look this modular structure
https://github.com/baconfy/skeleton