How to Use Nwidart Package to Build on Laravel Modules?

Dec 16, 2022 . Admin

Hello Friends,

I'll demonstrate how to use the Nwidart package to construct the Laravel modules' structure in this post. This will assist us in creating clear, organised code for our application that is reusable for all of its modules and simple to maintain.

Because Laravel modules include their own controllers, models, resources, and other things, some developers advise implementing them. As long as it's not a base module that connects to other modules, this helps us avoid breaking our application even if we remove one of our Laravel modules.

Let's start installing our Laravel modules right away.

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app
Step 2: Laravel Module Package Installation

Let's now install the Laravel module package developed by Nwidart. Run the following command:

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 example-app/composer.json
"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    
Step 5: Create Module

Then run the following command to create module let's do an example for test module.

php artisan module:make test    

After running above commands it will generate our test module under Modules folder. See below Laravel module structures:

    ├── test/
        ├── Config/
        ├── Console/
        ├── Database/           
            ├── factories/  
            ├── Migrations/
            ├── Seeders/
        ├── Entities/
        ├── Http/
            ├── Controllers/
            ├── Middleware/
            ├── Requests/
        ├── Providers/
            ├── testServiceProvider.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 test module. Let's test it by running the command below:

php artisan serve    

Then run the URL to your browser:

I hope it can help you...