Modules in Laravel

In order to write modular applications, a laravel-modules package has been created by nWidart which provides the ability to write modules in Laravel 5, a feature not provided by the framework out of the box.

The package is installed via Composer, a few adjustments are made to the Laravel application and then you’re ready to start writing modular code.

Start off by installing the package.

$ composer require nwidart/laravel-modules

Next, perform the below adjustment to the Laravel application.

Add the following service provider into the providers array within the config/app.php file..

Nwidart\Modules\LaravelModulesServiceProvider::class,

Now add the below alias into the aliases array in the same file.

'Module' => Nwidart\Modules\Facades\Module::class,

Next publish the package’s configuration file by running the below command.

$ /path/to/your/php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider"

The Laravel modules will belong in your project’s Modules directory, and are not autoloaded by default. This can be resolved by adding in a psr-4 entry within composer.json.

// composer.json

{
  "autoload": {
    "psr-4": {
      "App\\": "app/",
      "Modules\\": "Modules/"
    }
  }
}

Finally, update the autoloader by running Composer’s dump-autoload command.

$ composer dump-autoload

If you have correctly followed the above steps, you should be able to create a new module using module:make, passing in the name of the module.

$ /path/to/your/php artisan module:make MyModule

A MyModule directory will be created within the Modules directory within the Laravel root directory.

You can head to the mymodule route and you should notice that the Laravel Modules package has successfully rendered a view.

Modules in Laravel

The routes configuration resides within the module’s Http/routes.php file.

// Modules/MyModule/Http/routes.php

<?php

Route::group(['middleware' => 'web', 'prefix' => 'mymodule', 'namespace' => 'Modules\MyModule\Http\Controllers'], function()
{
    Route::get('/', 'MyModuleController@index');
});

As seen in the namespace array key, the MyModuleController controller created exists in Modules\MyModule\Http\Controllers.

Views are kept within the module’s Resources/views directory. You’ll see that there is an additional layouts directory that contains a master.blade.php file. This file renders the HTML5 doctype, <head> and <body> tags.

The index.blade.php file is responsible for rendering the main content seen within the screenshot above.

// Modules/MyModule/Resources/views/index.blade.php

@extends('mymodule::layouts.master')

@section('content')
    <h1>Hello World</h1>

    <p>
        This view is loaded from module: {!! config('mymodule.name') !!}
    </p>
@stop

You can use this modules package and the files that it creates to create your own module application.

Note: This article is based on Laravel version 5.4.