Igor Simic
4 years ago

Laravel - move controllers and modules to custom folder


If you want to have a modular kind of structure, where you will put all files which are belonging to one module (for example Auth module) including Controllers, Modules, Services.. there is a couple of things you have to change in Laravel settings.

So let's say we want to have a folder Http/Modules and inside we will have module Auth, and this folder will contain all needed files for that module
Controllers, Models, Services
App
- Http
-- Modules
--- Auth_Module
---- Controllers
---- Models
---- Services
By default Laravel will look in Http/Controllers folder to look for Controllers, in order to change this , we have to modify Providers/RouteServiceProviders.php and change 
protected $namespace = 'App\Http\Controllers'
to 
protected $namespace = ''
But remember, now every time when you include your controller you will have to insert full insert full namespace. For example, now in routes you will have a route to login like this:
Route::post('login', 'App\Http\Modules\Auth_Module\Controllers\AuthController@login');
In order to move models, to our new folder you can just create them there, but if you want to move User.php model to a new folder - in this case you have to inofrm Laravel and make this change inside of config/auth.php
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

],
to
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Http\Modules\Auth_Module\Models\User::class,
    ],

],
And one more thing, now when you want to generate controller using artisan command, you have to use relative paths:
php artisan make:controller ../Modules/Auth_Module/Controllers/AuthController