Simple Laravel Modules
There are already packages for a modular approach in laravel, but some packages are quite over-kill for what I need. So this is how I solved my modular approach in laravel.
Before we start, what is a module? For me, a module is part of an application which is composed of different types of resources, files and/or classes and when combined together gives a whole and a complete set of functionality. In laravel, a module should consist of the following: a route, a controller, a view and other necessary classes to achieve the target purpose of the module.
Why we need modules or modular setup? Modularity is one of the good principles and quality of a good architecture because of the following reasons:
- First, the codes which are related to each other are packaged together which means it has a good organization and cohesion.
- Second, it is giving you easier navigation when working with those files.
Now, let’s say you already have a fresh install of your new laravel app. And, your app is currently composed of two modules, Home
and About
.
The first thing you need to do is to design your directory structure. The simplest I can recommend is like this:
Notice that each module should have its routes definitions and its main controller which is mapped in the routes.
Let’s try to define your Home
route and controller.
app/Modules/Home/routes.php
app/Modules/Home/MainController.php
Notice that this is a usage of laravel’s Single Action Controller.
Now, to make this work open and edit your app/routes/web.php
to look like this:
Then try opening your browser and access the route to see that it works. Then after that, you can also do the same for the About
module.
Currently, we are just returning a string from out controller but in real life application, we may want to return blade views. Let me show you how it will be done in a modular way. Your blade views can be packaged inside your modules so your directory structure will look like this:
To make this work, we need to register these module folders as view locations inside the AppServiceProvider
boot()
method. So let’s open and edit app/Providers/AppServiceProvider
to look like this:
Now, you may return view inside the controller like this:
Then try to put any markup and text like <h1>This is the Home Page</h1>
inside your app/Modules/Home/home/index.blade.php
and reload your browser again and this should work.
Now, you have a complete simple setup of a modular laravel application. Imagine your application grow, then how easy it is to add new features or modules in your application. Btw, you can also add javascript and css files inside your module folders, so everything about your module is intact.
Happy Coding!!!