PHPackages                             strides/laravel-api-module - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. strides/laravel-api-module

ActiveLibrary[API Development](/categories/api)

strides/laravel-api-module
==========================

A code generation toolkit for building clean, scalable Laravel APIs with modular architecture.

v1.1.3(2w ago)111MITPHPPHP &gt;=8.1

Since Jul 21Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Strides-hovo/Laravel-api-module)[ Packagist](https://packagist.org/packages/strides/laravel-api-module)[ RSS](/packages/strides-laravel-api-module/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (6)Dependencies (12)Versions (18)Used By (0)

🧩 Laravel API Module
====================

[](#-laravel-api-module)

### Modular architecture &amp; code generator for Laravel APIs

[](#modular-architecture--code-generator-for-laravel-apis)

> A code generation toolkit for building clean, scalable Laravel APIs with modular architecture. Designed for teams that work exclusively with APIs and follow the **Action → Repository → Transformer** pattern.

![Latest Version](https://camo.githubusercontent.com/4f7e0d0b2eb3de8c977c19f21c7250bee9dcbaef07d742736035565ed3a1f2e6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c7565)![PHP](https://camo.githubusercontent.com/0ea8169f9f11e788c33170bd1db459e10d7b6a8df60aba22778797ffbc54969d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e312d3737374242343f7374796c653d666c6174266c6f676f3d706870266c6f676f436f6c6f723d7768697465)![Laravel](https://camo.githubusercontent.com/24a464d6a23434cbb0030ac7ec3078955b9396922da6a528106996f72d7fd5f1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f496c6c756d696e6174652d253545392e3025323025374325323025354531302e3025323025374325323025354531312e3025323025374325323025354531322e3025323025374325323025354531332e302d4646324432303f7374796c653d666c6174266c6f676f3d6c61726176656c266c6f676f436f6c6f723d7768697465)![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)

---

Why This Package?
-----------------

[](#why-this-package)

When building APIs with Laravel, you end up creating the same set of files for every resource: model, migration, controller, request, repository, transformer, action, and so on. This package automates that with Artisan generators designed specifically for API development — no Blade views, no web routes, no frontend scaffolding.

```
php artisan module:make-model Product --all
```

One command. Model, migration, factory, seeder, controller, repository, transformer — all generated with correct namespacing, PSR-12 formatting, and placed in an isolated module directory.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Module Management](#module-management)
- [Generators Reference](#generators-reference)
- [Architecture Pattern](#architecture-pattern)
- [Configuration](#configuration)
- [Migration Commands](#migration-commands)
- [Testing](#testing)
- [Support](#support)

---

Requirements
------------

[](#requirements)

DependencyVersionPHP`>= 8.1`Laravel`^9.0 | ^10.0 | ^11.0 | ^12.0 | ^13.0`ComposerLatest---

[![Demo](module.gif)](module.gif)

Installation
------------

[](#installation)

**1. Install via Composer**

```
composer require strides/laravel-api-module
```

**2. Publish configuration**

```
php artisan vendor:publish --provider="Strides\Module\Providers\ModuleServiceProvider"
```

**3. Register the Modules namespace in `composer.json`**

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

```
composer dump-autoload
```

**4. Add Modules test suite to `phpunit.xml`** *(optional but recommended)*

```

        Modules/*/Tests/*

```

Quick Start
-----------

[](#quick-start)

### Create a complete module

[](#create-a-complete-module)

```
php artisan module:make-module Product
```

This registers the module in `modules_name.json` and generates the full directory structure:

```
Modules/
└── Product/
    ├── Actions/
    ├── Database/
    │   ├── Factories/
    │   ├── Migrations/
    │   └── Seeders/
    ├── Entities/
    ├── Events/
    ├── Http/
    │   ├── Controllers/
    │   ├── Middleware/
    │   ├── Requests/
    │   ├── Resources/
    │   └── Transformers/
    ├── Jobs/
    ├── Listeners/
    ├── Providers/
    ├── Repositories/
    ├── Services/
    └── Tests/

```

Configuration
-------------

[](#configuration)

Publish and edit `config/module.php` to customize module structure:

```
return [
    'namespace'    => 'Modules',
    'modules'      => base_path('Modules'),
    'modules_name' => base_path('modules_name.json'),

    // Format generated .php files with laravel/pint (PSR-12) after creation.
    // Requires "laravel/pint" in require-dev. Silently skipped if not installed.
    'format_with_pint' => true,

    'paths' => [
        'modules' => base_path('Modules'),

        'generator' => [
            'model'        => ['path' => 'Entities',          'generate' => true],
            'migration'    => ['path' => 'Database/Migrations','generate' => true],
            'seeder'       => ['path' => 'Database/Seeders',   'generate' => true],
            'factory'      => ['path' => 'Database/Factories', 'generate' => false],

            'repository'   => ['path' => 'Repositories',       'generate' => true],
            'transformer'  => ['path' => 'Http/Transformers',  'generate' => true],
            'middleware'   => ['path' => 'Http/Middleware',    'generate' => false],
            'controller'   => ['path' => 'Http/Controllers',   'generate' => true],
            'request'      => ['path' => 'Http/Requests',      'generate' => true],
            'resource'     => ['path' => 'Http/Resources',     'generate' => false],
            'service'      => ['path' => 'Services',           'generate' => false],
            'action'       => ['path' => 'Actions',            'generate' => true],

            'mail'         => ['path' => 'Mail',               'generate' => false],
            'notification' => ['path' => 'Notification',       'generate' => false],
            'dto'          => ['path' => 'Dto',                'generate' => false],
            'rule'         => ['path' => 'Http/Rules',          'generate' => false],
            'policy'       => ['path' => 'Policies',           'generate' => false],
            'command'      => ['path' => 'Console/Commands',   'generate' => false],

            'event'        => ['path' => 'Events',             'generate' => false],
            'listener'     => ['path' => 'Listeners',          'generate' => false],
            'job'          => ['path' => 'Jobs',               'generate' => false],
            'cast'         => ['path' => 'Casts',              'generate' => false],
            'http'         => ['path' => '/',                  'generate' => true],

            'unit_test'    => ['path' => 'Tests/Unit',         'generate' => false],
            'feature_test' => ['path' => 'Tests/Feature',      'generate' => false],
        ],
    ],
];
```

Module Management
-----------------

[](#module-management)

Every module is registered in `modules_name.json` at the project root. The package provides four commands to manage module lifecycle.

### List all modules

[](#list-all-modules)

```
php artisan module:list
```

```
+------------+-----------+--------------+----------------------------------+
| Module     | Status    | Path exists  | Path                             |
+------------+-----------+--------------+----------------------------------+
| Product    | Enabled   | ✓            | /var/www/Modules/Product         |
| Orders     | Disabled  | ✓            | /var/www/Modules/Orders          |
| Legacy     | Enabled   | ✗ Missing    | /var/www/Modules/Legacy          |
+------------+-----------+--------------+----------------------------------+

Total: 3  Enabled: 2  Disabled: 1  Missing: 1

```

### Enable / Disable a module

[](#enable--disable-a-module)

```
php artisan module:enable  Orders
php artisan module:disable Orders
```

Disabling a module prevents its service provider from loading — routes, migrations, and commands become inactive. Files are preserved.

### Clean up stale entries

[](#clean-up-stale-entries)

```
php artisan module:optimize
```

Scans `modules_name.json` and removes entries whose directories no longer exist. Asks for confirmation before writing.

```
The following modules have no directory and will be removed:
  - Legacy

Proceed? (yes/no) [yes]:
Done. Removed 1 stale entry from modules_name.json.

```

---

Generators Reference
--------------------

[](#generators-reference)

### Module

[](#module)

CommandDescription`module:make-module {name}`Create a complete module with full directory structure### Models &amp; Data

[](#models--data)

CommandFlagsDescription`module:make-model {module} {name}``-m` `-c` `-f` `-s` `-a`Eloquent model with optional related files`module:make-migration {module} {name}`Database migration`module:make-seeder {module} {name}`Database seeder`module:make-factory {module} {name}`Model factory**Model flags:**

FlagLongGenerates`-m``--migration`Migration`-c``--controller`Controller`-f``--factory`Factory`-s``--seeder`Seeder`-a``--all`All of the above### Controllers &amp; HTTP

[](#controllers--http)

CommandFlagsDescription`module:make-controller {module} {name}``-r` `-s` `-c` `-p` `-m` `-a`API controller`module:make-request {module} {name}`FormRequest validation class`module:make-transformer {module} {name}`Data transformer for API responses**Controller flags:**

FlagLongGenerates`-r``--request`FormRequest class`-s``--resource`API Resource class`-c``--collection`Resource Collection class`-p``--repository`Repository class`-m``--model`Model name for type hints`-a``--all`All of the above`-T``--test`Unit test### Business Logic

[](#business-logic)

CommandDescription`module:make-action {module} {name}`Single-purpose invokable action class`module:make-service {module} {name}`Service class for complex operations`module:make-repository {module} {name}`Repository for data access abstraction### Events &amp; Async

[](#events--async)

CommandFlagsDescription`module:make-event {module} {name}``--listener[=Name]`Event class. Optionally creates a linked Listener`module:make-listener {module} {name}``--event=ClassName`Listener. `--event=` typehints the `handle()` parameter`module:make-job {module} {name}`Queueable job (`ShouldQueue` by default)**Event → Listener examples:**

```
# Create Event only
php artisan module:make-event Product ProductCreated

# Create Event + auto-generate a linked Listener
php artisan module:make-event Product ProductCreated --listener

# Create Event + Listener with a specific name
php artisan module:make-event Product ProductCreated --listener=SendProductNotification

# Create Listener with typed handle(ProductCreated $event)
php artisan module:make-listener Product SendProductNotification --event=ProductCreated
```

### Utilities

[](#utilities)

CommandDescription`module:make-middleware {module} {name}`HTTP middleware`module:make-test {module} {name} {type} default = unit`Unit or Feature test class---

Architecture Pattern
--------------------

[](#architecture-pattern)

### Action → Repository → Transformer

[](#action--repository--transformer)

This package is built around a clean three-layer API architecture:

```
HTTP Request
    │
    ▼
FormRequest (validation)
    │
    ▼
Controller  ──────────────────────────────┐
    │                                      │
    ▼                                      │
Action (business logic)                   │
    │                                      │
    ▼                                      │
Repository (data access)                  │
    │                                      │
    ▼                                      │
Transformer (response format) ◄───────────┘
    │
    ▼
JSON Response

```

Transformers
------------

[](#transformers)

The package provides a robust data transformation layer using `ModuleTransformer` and `TransformerCollection`. It extends Laravel's native API Resources to standardize JSON outputs, enforce strict performance guidelines (preventing accidental N+1 queries), and streamline handling of single models, collections, and paginated data.

### 1. Creating a Transformer

[](#1-creating-a-transformer)

Every custom transformer must extend `Strides\Module\Transformers\ModuleTransformer` and implement the abstract **`transformModel($model): array`** method.

#### Example Implementation

[](#example-implementation)

```
namespace App\Modules\User\Transformers;

use Strides\Module\Transformers\ModuleTransformer;

class UserTransformer extends ModuleTransformer
{
    /**
     * Define which relations are allowed to be included via query string.
     */
    protected array $availableIncludes = ['posts', 'profile'];

    /**
     * Abstract method that MUST be implemented.
     * Defines the raw transformation for a single model instance.
     *
     * @param \App\Models\User $model
     */
    public function transformModel($model): array
    {
        return [
            'id'    => $model->id,
            'name'  => $model->name,
            'email' => $model->email,
        ];
    }

    /**
     * Optional: Custom include method for 'posts' relation.
     * If omitted, the transformer will fallback to automatic $relatedData->toArray().
     */
    public function includePosts($posts)
    {
        // You can leverage another transformer for the relation
        return PostTransformer::collection($posts);
    }
}
```

### Component generators

[](#component-generators)

Each command: `php artisan module:make-  `.

CommandGeneratesKey flags`module:make-controller`Controller`--request`, `--resource`, `--transformer`, `--service`, `--action`, `--test`, `--all``module:make-model`Eloquent model`--migration`, `--controller`, `--request`, `--resource`, `--service`, `--transformer`, `--policy`, `--factory`, `--seed`, `--pivot`, `--morph-pivot`, `--test`, `--all``module:make-service`Service class—`module:make-repository`Repository class`--model``module:make-action`Action class (Index/Store/Update/Destroy)—`module:make-request`Form Request—`module:make-resource`API Resource`--collection``module:make-transformer`Transformer—`module:make-rule`Validation rule—`module:make-policy`Policy`--model`, `--guard``module:make-factory`Model factory`--model``module:make-seeder`Seeder—`module:make-middleware`Middleware—`module:make-event`Event class—`module:make-listener`Listener class`--event``module:make-job`Job class—`module:make-mail`Mailable class`--view``module:make-notification`Notification class—`module:make-dto`DTO class—`module:make-command`Module-scoped Artisan command—### Per-module migrations

[](#per-module-migrations)

CommandDescription`module:make-migration {module} {name}`Creates a migration file inside the module.`module:migrate {module}`Runs the module's migrations.`module:migrate-status {module}`Shows migration status for the module.`module:migrate-rollback {module}`Rolls back the last migration batch.`module:migrate-reset {module}`Rolls back all migrations.`module:migrate-refresh {module}`Resets and re-runs migrations.`module:migrate-fresh {module}`Drops and recreates tables (`--drop-views`, `--drop-types`).Standard Laravel flags apply where relevant: `--force`, `--seed`, `--seeder`, `--database`, `--pretend`, `--step`.

---

6. Example
----------

[](#6-example)

```
# Create the module
php artisan module:make-module Blog

# Model + migration + factory + seeder + policy + controller + test
php artisan module:make-model Blog Post --all

# Controller side: request + resource + transformer + service + action + test
php artisan module:make-controller Blog Post --all

# Run this module's migrations only
php artisan module:migrate Blog --seed

# Toggle the module on/off without deleting it
php artisan module:disable Blog
php artisan module:enable Blog
```

```
php artisan module:make-controller Blog --all

class BlogController extends Controller
{
    public function index(BlogRequest $request, BlogIndexAction $action): TransformerCollection
    {
        $blogs = $action->handle($request->validated());

        return BlogTransformer::collection($blogs, 200);
    }

    public function store(BlogRequest $request, BlogStoreAction $action): ModuleTransformer
    {
        $blog = $action->handle($request->validated());

        return BlogTransformer::make($blog, 201);
    }

    public function update(int|string $id, BlogRequest $request, BlogUpdateAction $action): ModuleTransformer
    {
        $blog = $action->handle($id, $request->validated());

        return BlogTransformer::make($blog, 200);
    }

    public function destroy(int|string $id, BlogDestroyAction $action): JsonResponse
    {
        $action->handle($id);

        return response()->json(null, 204);
    }
}
```

Troubleshooting
---------------

[](#troubleshooting)

**Migrations not found**Ensure the module is registered in `modules_name.json` (it happens automatically when you use `module:make-module` or any `module:make-*` command). If you created files manually, run `module:optimize` to sync the file.

**Classes not autoloading**Run `composer dump-autoload` after adding `"Modules\\": "Modules/"` to your `composer.json`.

**Service provider not loading**Verify that `modules_name.json` contains your module name with `true`. Use `php artisan module:list` to inspect the state.

**Queue jobs not processing**Jobs generated by `module:make-job` implement `ShouldQueue` by default. Ensure your queue driver is configured in `.env` (`QUEUE_CONNECTION=redis` or similar) and a worker is running.

---

Testing
-------

[](#testing)

**OK (14 tests, 227 assertions)**

License
-------

[](#license)

MIT — see [LICENSE](LICENSE).

---

Support
-------

[](#support)

- 🐛 **Bug reports:** [GitHub Issues](https://github.com/Strides-hovo/Laravel-api-module/issues)
- 💬 **Discussions:** [GitHub Discussions](https://github.com/Strides-hovo/Laravel-api-module/discussions)

---

*Inspired by [nWidart/laravel-modules](https://github.com/nWidart/laravel-modules). Built for teams that live in the API layer.*

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance93

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~104 days

Recently: every ~2 days

Total

10

Last Release

18d ago

Major Versions

1.1.2 → 2.0.02026-06-23

### Community

Maintainers

![](https://www.gravatar.com/avatar/10c4116cd468cf6bebae6de734403f44ee7ad1f00eea675bf157fe84ffca9d3c?d=identicon)[Strides-hovo](/maintainers/Strides-hovo)

---

Top Contributors

[![Strides-hovo](https://avatars.githubusercontent.com/u/54514516?v=4)](https://github.com/Strides-hovo "Strides-hovo (25 commits)")

---

Tags

action-patternapiartisancode-generatorlaravellaravel-packagemodular-architecturemodulephprepository-patterntransformerlaravelmodulemodulesstrides

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/strides-laravel-api-module/health.svg)

```
[![Health](https://phpackages.com/badges/strides-laravel-api-module/health.svg)](https://phpackages.com/packages/strides-laravel-api-module)
```

###  Alternatives

[defstudio/telegraph

A laravel facade to interact with Telegram Bots

818355.4k3](/packages/defstudio-telegraph)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5226.7k](/packages/simplestats-io-laravel-client)[riclep/laravel-storyblok

A Laravel wrapper around the Storyblok API to provide a familiar experience for Laravel devs

6281.2k5](/packages/riclep-laravel-storyblok)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
