How to structure a modular app in Laravel 5?

Published on Author Code Father

Solution:

Step1: Create Folder “Modules” inside “app/”


Step2: In Modules folder create your Module (Module1( suppose admin Module))

 Inside admin module : create the following folder 

 1. Controllers  (here will your controller files)
 2. Views  (here will your View files)
 3. Models  (here will your Model files)
 4. routes.php (here will your route code in this file)

Similarly, You can create another module

Module2( suppose API )
-Controllers
-Views
-Models
-routes.php

Similarly, you can create multiple modules


Step3 : Create ModulesServiceProvider.php inside “Modules/” Folder


Step4 : Paste following code inside ModulesServiceProvider.php

<?php

namespace App\Modules;

/**
* ServiceProvider
*
* The service provider for the modules. After being registered
* it will make sure that each of the modules are properly loaded
* i.e. with their routes, views etc.
*
* @author kundan Roy <query@programmerlab.com>
* @package App\Modules
*/

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class ModulesServiceProvider extends ServiceProvider
{

/**
* Will make sure that the required modules have been fully loaded
* @return void routeModule
*/
public function boot()
{
// For each of the registered modules, include their routes and Views
$modules = config(“module.modules”);

while (list(,$module) = each($modules)) {

// Load the routes for each of the modules

if(file_exists(DIR.’/’.$module.’/routes.php’)) {

include DIR.’/’.$module.’/routes.php’;
}

if(is_dir(DIR.’/’.$module.’/Views’)) {
$this->loadViewsFrom(DIR.’/’.$module.’/Views’, $module);
}
}
}

public function register() {}

}

Step5 : Add following line inside ‘config/app.php’ file

App\Modules\ModulesServiceProvider::class,

Step6 : Create module.php file inside ‘config’ folder

Step7 : Add following code inside module.php (path => “config/module.php”)

<?php

return  [
modules => [
admin’,
web’,
api
]
];

Note : You can add your module name whichever you have created. Here there are modules.

Step8 : Run this command

composer dump-autoload

Thanks 🙂

Comments

comments