Table of contents
In this post, I will show you how to implement Laravel modules structure in with Nwidart package. This will help us to make our application clean and organized code that is easy to maintain and reusable to any modules within the application.
Â
Some developers recommend implementing a Laravel modules because it comes with own controllers, model, resources and more. That help us not to break our application even if we remove one of our laravel module as long as not a base module that connect with other modules.
Â
Codeanddeploy also using laravel module structures.
Â
When using Laravel modules it will generate with the following:
Â
1. Config
2. Console
3. Database
4. Entities
5. Http
6. Providers
7. Resources
8. Routes
9. Tests
Â
Now let's start installing our Laravel modules.
Â
Step 1: Laravel Installation
If you don't have a Laravel 8 install in your local just run the following command below:
composer create-project --prefer-dist laravel/laravel laravel-modules-example
cd laravel-modules-example
Â
Â
Step 2: Laravel Module Package Installation
Now, let's install our Laravel module package by Nwidart. Run the following command below:
composer require nwidart/laravel-modules
Â
Step 3: Publish Configuration File
Run the following command to publish the configuration file.
php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider"
Â
Step 4: Setup Autoloading
Now, we need to add "Modules\\":
"Modules/",
to your composer under autoload
> psr-4
. See example below:
"autoload": {
"psr-4": {
"App\\": "app/",
"Modules\\": "Modules/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
Â
Then run the following command after setup above:
composer dump-autoload
Â
Now, we already setup our Laravel module package. Next let's create a module for our Laravel application.
Â
Step 5: Create Module
Syntax of create module command:
php artisan make:module module_name
Â
Then run the following command to create module let's do an example for Posts module.
php artisan make:module posts
Â
After running above commands it will generate our Posts module under Modules folder. See below Laravel module structures:
app/
bootstrap/
vendor/
Modules/
├── Posts/
├── Assets/
├── Config/
├── Console/
├── Database/
├── Migrations/
├── Seeders/
├── Entities/
├── Http/
├── Controllers/
├── Middleware/
├── Requests/
├── Providers/
├── PostsServiceProvider.php
├── RouteServiceProvider.php
├── Resources/
├── assets/
├── js/
├── app.js
├── sass/
├── app.scss
├── lang/
├── views/
├── Routes/
├── api.php
├── web.php
├── Repositories/
├── Tests/
├── composer.json
├── module.json
├── package.json
├── webpack.mix.js
Â
Now, we successfully generated our Posts
module. Let's test it by running the command below:
php artisan serve
Â
Then run the URL to your browser:
http://127.0.0.1:8000/posts
Â
Then you will see the result below:
I hope it helps. For more details about it click Laravel modules.
Read next