What is a Laravel modular monolith and why do boundaries matter more than folders?

A Laravel modular monolith is a single deployable application, with one codebase, one deploy pipeline and usually one database server, that is split internally into domain modules such as Billing, Catalog and Identity. Each module owns its code, its tables and its own registration with the framework: routes, bindings, event listeners and migrations. Teams can work in parallel inside one repository without paying for network calls, distributed transactions and separate deployments before they need them.

The default Laravel skeleton groups code by technical layer: app/Http/Controllers, app/Models, app/Jobs. That layout says nothing about which code belongs to which part of the business. An InvoiceController can import Product and User directly. A Product model can gain an invoices() relationship. Over time every model can reach every other model through Eloquent. A change to how customers are stored then breaks checkout, reporting and email at once. Moving files into module folders does not fix this. A boundary only exists when something stops code from crossing it, which is why later sections cover enforcement.

Draw boundaries from business capabilities, not from database tables. Ask what the business does: take payments, maintain a catalog, authenticate people. Each capability usually maps to a bounded context, which is a region where terms keep one consistent meaning. "Product" in Catalog has descriptions and images. In Billing it is a price line and a tax code. When the same word means different things in different places, that difference is a strong sign of a module boundary.

LAYER-BASED SPLIT: folders by technical role, any model reaches any model
+------------------------------------------------------------------------+
| app/Http/Controllers InvoiceController   ProductController             |
|                         |                |                             |
|                         v                v                             |
| app/Models           Invoice <---> Product <---> User                  |
|                         ^             |           ^                    |
|                         +-------------+-----------+  any-to-any links  |
+------------------------------------------------------------------------+
  change how User is stored -> checkout, reporting and email all break

MODULAR MONOLITH: one deployable app, modules split by business capability
+------------------------------------------------------------------------+
|  Laravel app: one codebase, one deploy pipeline, one database server   |
| +--------------------+  +--------------------+  +--------------------+ |
| | Billing            |  | Catalog            |  | Identity           | |
| | routes, migrations |  | routes, migrations |  | routes, migrations | |
| | bindings, listeners|  | bindings, listeners|  | bindings, listeners| |
| | own tables         |  | own tables         |  | own tables         | |
| | Product: price,    |  | Product: text,     |  | User: credentials  | |
| |   tax code         |  |   images           |  |   sessions         | |
| +---------+----------+  +---------+----------+  +---------+----------+ |
|           |                       |                       |            |
|           +-----------------------+-----------------------+            |
|    public interfaces and domain events only; no cross-module models    |
+------------------------------------------------------------------------+
  folders alone are not a boundary; enforcement blocks the crossings

A layer-based layout lets every Eloquent model reach every other, while a modular monolith gives each bounded context its own code, tables and registration and allows contact only through public interfaces and events.

Who should use a modular monolith, and when should you avoid it?

The pattern pays off when several teams or several distinct domains share one codebase. If the Catalog team and the Billing team both merge into the same repository every day, the cost of accidental coupling shows up as merge conflicts, surprise regressions and long review threads about who owns a model. Explicit modules give each team a surface it controls and a small, named contract it must keep stable for everyone else.

When to adopt it

Adopt it once the domain is reasonably well understood and coordination costs are visibly rising. Useful signals include changes in one area that keep breaking another, a few Eloquent models that every feature touches, and onboarding that requires a tour of the whole app/ directory. At that point you know where the seams are. You are drawing boundaries around something real instead of guessing.

When to avoid it

Skip it for small teams, simple CRUD applications, and domains that are still shifting. Boundaries drawn too early tend to land in the wrong place. Modules that should have been one end up calling each other constantly, passing data back and forth through interfaces that exist only to satisfy the structure. Undoing that means moving code, renaming namespaces and rewriting contracts, which usually costs more than never having split.

The development cost

The structure adds weight. You write interfaces for cross-module calls, DTOs instead of passing models around, and a service provider per module. Tooling that assumes app/ also needs extra configuration, including static analysis paths, test suite discovery and code generators.

How do you lay out Laravel modules with PSR-4 namespaces?

Pick one root, modules/ or src/, and give each domain a single top-level folder named after the business capability, such as Billing, Catalog or Identity. Avoid technical layers like Models or Http at this level. A module folder for Billing might contain:

  • Routes/ for web.php and api.php, loaded only by the module's provider
  • Database/Migrations/ and Database/Factories/
  • Config/billing.php, merged under its own key so nothing collides with core config
  • Resources/views/, registered under a billing:: namespace
  • Tests/Unit and Tests/Feature, kept next to the code they cover
  • Internal/ for models, actions, jobs and controllers
  • Contracts/ for the interfaces, DTOs and events other modules may depend on

Splitting Internal and Contracts is the most important choice in this layout. The namespace alone tells you whether a dependency is allowed, so a reviewer or a static rule only has to check that Modules\Catalog\... never imports Modules\Billing\Internal\....

Autoloading takes one entry in the root composer.json under autoload.psr-4, mapping "Modules\\" to "modules/". Add a matching autoload-dev entry if tests live in their own namespace, then run composer dump-autoload.

Expect two gaps in tooling. Artisan generators such as make:model write into app/ with the App\ namespace, so you have to move the files and fix the namespaces yourself, add a thin wrapper command, or use stub customisation. Package auto-discovery only reads extra.laravel from installed packages in vendor/, not from folders inside your own repository. Register each module's service provider explicitly in the application's provider list.

modules/
└── Billing/                        # one folder per business capability
    ├── BillingServiceProvider.php  # Modules\Billing\BillingServiceProvider
    ├── Routes/
    │   ├── web.php                 # loaded only by BillingServiceProvider
    │   └── api.php
    ├── Database/
    │   ├── Migrations/             # registered via loadMigrationsFrom()
    │   └── Factories/
    ├── Config/
    │   └── billing.php             # mergeConfigFrom(..., 'billing')
    ├── Resources/
    │   └── views/                  # loadViewsFrom(..., 'billing') -> billing::invoice
    ├── Tests/
    │   ├── Unit/
    │   └── Feature/
    ├── Internal/                   # Modules\Billing\Internal\... (private to Billing)
    │   ├── Models/
    │   ├── Actions/
    │   ├── Jobs/
    │   └── Http/Controllers/
    └── Contracts/                  # Modules\Billing\Contracts\... (the only public surface)
        ├── InvoiceGateway.php      # interface other modules type-hint
        ├── InvoiceData.php         # DTO
        └── InvoicePaid.php         # event

# composer.json (root) - one prefix covers every module, including Tests/
"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Modules\\": "modules/"
    }
}

# Then: composer dump-autoload
# Auto-discovery does not scan modules/, so register providers yourself:
# bootstrap/providers.php (Laravel 11+) or the 'providers' array in config/app.php
#     Modules\Billing\BillingServiceProvider::class,

A Billing module laid out under modules/ with separate Internal and Contracts namespaces, the single PSR-4 mapping that autoloads it, and the manual provider registration that auto-discovery does not handle.

How do service providers act as each module's composition root?

Each module gets one provider, such as Modules\Billing\BillingServiceProvider, and that class is the only place where the module's internals are wired to the rest of the application. In register(), it binds contracts to implementations, for example InvoiceRepository to EloquentInvoiceRepository. register() must contain only container bindings. Other providers may not have run yet, so resolving services or touching config here can fail depending on provider order.

boot() runs after every provider has registered, so it can safely depend on the rest of the framework:

  • Routes: loadRoutesFrom mounts the module's routes. It is skipped when routes are cached.
  • Migrations: loadMigrationsFrom adds the module's migrations directory to php artisan migrate.
  • Views: loadViewsFrom registers a view namespace, so templates resolve as billing::invoice and never collide with another module's.
  • Listeners: the module subscribes to events it cares about, such as Event::listen(OrderPlaced::class, CreateInvoice::class).
  • Config: mergeConfigFrom supplies defaults the host app can override. Laravel's own convention places this call in register(), so other providers' code sees the merged values. Either way, it has no effect once config is cached.

Because the provider is the module's whole surface, removing it from the provider list disables the module completely. A test case can boot only the providers it needs and swap a contract binding for a fake.

Every non-deferred provider runs on every request, so keep boot() to registration calls. Do not query the database or resolve heavy services there. For modules that only expose bindings, implement DeferrableProvider and list those bindings in provides(). Laravel will then load the provider only when one of those services is first resolved.

<?php
// PHP: modules/Billing/src/BillingServiceProvider.php
namespace Modules\Billing;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Modules\Billing\Contracts\InvoiceRepository;
use Modules\Billing\Listeners\CreateInvoice;
use Modules\Billing\Persistence\EloquentInvoiceRepository;
use Modules\Orders\Events\OrderPlaced; // public event from another module

class BillingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Container bindings only. Other providers may not have registered yet.
        $this->app->bind(InvoiceRepository::class, EloquentInvoiceRepository::class);

        // Merge defaults early so other providers see them.
        // The host app's config/billing.php overrides these keys.
        $this->mergeConfigFrom(__DIR__.'/../config/billing.php', 'billing');
    }

    public function boot(): void
    {
        // Registration calls only. No queries and no heavy resolution:
        // this runs on every request.
        $this->loadRoutesFrom(__DIR__.'/../routes/web.php');
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');

        // Templates resolve as view('billing::invoice').
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'billing');

        // Billing reacts to Orders without Orders knowing Billing exists.
        Event::listen(OrderPlaced::class, CreateInvoice::class);
    }
}

A per-module service provider in PHP that binds the Billing contract and merges config defaults in register(), then mounts routes, migrations, namespaced views and an event listener in a lightweight boot().

How should modules communicate and share data?

Treat everything outside a module's Contracts namespace as private. That namespace holds interfaces other modules may call, such as Billing\Contracts\InvoiceLookup, the read-only DTOs those interfaces return, and the domain events the module publishes. Eloquent models never cross the boundary. Returning a model gives callers lazy loading, save(), and every column, so your table schema becomes another team's API.

Injected contract (sync) Domain event + queued listener (async)
Consistency Immediate, can share a transaction Eventual
Coupling Caller depends on callee's interface Publisher doesn't know its listeners
Failure Caller sees the exception Retries, failed jobs, possible duplicates
Use when The caller needs the answer to continue Others react to something that already happened

Use a contract when correctness depends on the result, for example checking credit before accepting an order. Use an event when the work can lag, for example sending a receipt. Dispatch events after the transaction commits, and make listeners idempotent so retries are safe.

Each module owns its tables. Other modules store the foreign ID as a plain column, with no cross-module foreign key and no belongsTo relation. When another module needs that data, it calls a query service or reads a projection built from events.

This approach has costs. Screens that used one join now need several queries. Copied fields such as a customer name in an orders table go stale. Reports that span modules need a separate read model. Queued listeners can run out of order, and tracing one request across jobs requires correlation IDs in your logs.

<?php
// Billing/Contracts: the only Billing code other modules may import.
namespace Billing\Contracts;

interface InvoiceLookup
{
    // Sync API: returns a read-only DTO, never an Eloquent model.
    public function findForOrder(int $orderId): ?InvoiceSummary;
}

final readonly class InvoiceSummary
{
    public function __construct(
        public int $invoiceId,
        public int $orderId,
        public int $amountCents,
        public string $status,
    ) {}
}

// Async API: a published fact that carries IDs and values, not models.
final readonly class InvoicePaid
{
    public function __construct(public int $invoiceId, public int $orderId) {}
}

// Orders module: reacts to Billing without Billing knowing about it.
namespace Orders\Listeners;

use Billing\Contracts\InvoicePaid;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;

final class MarkOrderPaid implements ShouldQueue
{
    public $afterCommit = true; // queue only after Billing's transaction commits

    public function handle(InvoicePaid $event): void
    {
        // Idempotent: touches only Orders' own table, and a retry or duplicate is a no-op.
        DB::table('orders')->where('id', $event->orderId)->whereNull('paid_at')->update(['paid_at' => now()]);
    }
}

A Billing Contracts namespace exposing an interface, a readonly DTO and a domain event, consumed by an Orders queued listener that runs after commit and updates only its own table idempotently (PHP).

How do you enforce module boundaries in CI and test each module?

A boundary that exists only in a README stops holding the first time someone needs a shipping status inside Billing and the release is due that afternoon. Importing Modules\Shipping\Models\Shipment directly works, review misses it, and the next developer copies the pattern. Conventions erode because breaking them costs nothing at the moment it happens. CI has to make the violation fail.

Architecture tests and static analysis

Express the rule as code: a module may depend on its own namespace, the framework, and other modules' Contracts namespaces, and nothing else. Pest's architecture expectations can assert that Modules\Billing does not use Modules\Shipping\Models or Modules\Shipping\Internal. Deptrac takes a different route. It defines layers per module and an allowlist of dependencies between them, then reports every class reference that crosses an unlisted edge. Either one runs in seconds, so put it in the same pipeline stage as your linter. A coupling mistake then shows up in the pull request where it was introduced, which is far cheaper than finding it during an extraction months later.

Testing strategy

Each module owns its unit and feature tests under its own tests directory. When Billing depends on Shipping, bind a fake implementation of the Shipping contract in the container, and use Event::fake() or Queue::fake() to assert on cross-module messages without running the listeners. Billing's suite then fails only when Billing is broken. On top of that, keep a small set of end-to-end tests covering the critical flows that span modules, such as checkout through fulfilment. These verify the real wiring. The per-module suites stay fast enough to run on every change, and a failure points straight to the module that caused it.

How do you migrate an existing app/ codebase, and what are the alternatives?

Start with one domain the team already understands well, with few inbound dependencies. Billing or notifications often qualify, while a central "users" domain rarely does. Then work in this order:

  1. Introduce the contract first. Define the interface and data objects other code will call, and bind it in the new module's service provider. At this point the binding can still delegate to the old classes in app/. Callers switch to the contract before any code moves, so each of these changes stays small and reviewable.
  2. Move the implementation behind the contract. Relocate models, jobs and services into the module namespace. Because callers depend only on the interface, the move doesn't affect them.
  3. Tighten the boundary rules. Add the module to your architecture tests and remove its exceptions from the allowlist. Do this only after the code has moved, so the build isn't red while the work is still in progress.
  4. Repeat for the next domain. Each pass makes the remaining app/ code smaller and easier to reason about.
Approach Team scaling Deployment Independent scaling Fault isolation Development cost
Plain app/ Poor as teams grow One unit No None Lowest at first
Layered/DDD folders, unenforced Moderate, but erodes One unit No None Low
Modular monolith Good One unit No Logical only Moderate
Microservices Strong Per service Yes Process-level High

A modular monolith still shares one deployment, one database server and one runtime. A memory leak in one module can still take down every module, and a slow migration still blocks every release. If you need independent scaling or failure containment, the modular structure helps you prepare for it. The enforced contracts become the seams where you would later extract a service.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to laravel modular monolith, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.