What is Laravel modular architecture built on bounded contexts?

A Laravel modular architecture is a modular monolith: one deployable application, one codebase, usually one database, divided into modules that each own a business capability. Instead of the default app/ layout, where every model sits in app/Models and every controller in app/Http/Controllers, you get modules such as Billing, Catalog and Fulfillment. Each module contains its own models, controllers, jobs, events, migrations and service provider. The split follows the business, not technical layers.

Bounded contexts supply the boundaries. In Catalog, a "Product" has descriptions, images and categories. In Billing, the same product is a price, a tax class and a line item. Modelling these as separate concepts in separate modules keeps one shared Product class from collecting every team's columns and conditionals. The boundary also has to exist in code, not only in a diagram: Billing calls a public interface that Catalog exposes and does not query Catalog's tables directly.

For a large Laravel app, this is usually a better destination than an early move to microservices. You get clear seams without network calls, distributed transactions or separate deploy pipelines. If a module later needs to become its own service, its boundary is already drawn.

The approach suits long-lived codebases where several developers or teams work in different business areas. It saves engineering time in two ways:

  • Smaller change surfaces: a change to refund logic touches Billing and nothing else, so reviews are faster and regressions are rarer.
  • Clearer ownership: each module has an obvious owner, which settles questions about who reviews a change and who gets paged.
+--------------------------------------------------------------------------+
|     ONE DEPLOYABLE LARAVEL APP  (one codebase, one deploy pipeline)      |
|                                                                          |
|  +--------------------+  +--------------------+  +--------------------+  |
|  | Billing            |  | Catalog            |  | Fulfillment        |  |
|  |--------------------|  |--------------------|  |--------------------|  |
|  | models, controllers|  | models, controllers|  | models, controllers|  |
|  | jobs, events       |  | jobs, events       |  | jobs, events       |  |
|  | migrations         |  | migrations         |  | migrations         |  |
|  | ServiceProvider    |  | ServiceProvider    |  | ServiceProvider    |  |
|  |                    |  |                    |  |                    |  |
|  | Product = price,   |  | Product = text,    |  | Order = parcel,    |  |
|  |   tax class        |  |   images, category |  |   carrier, status  |  |
|  +---------+----------+  +---------+----------+  +--------------------+  |
|            |                       |                                     |
|            |             +---------+----------+                          |
|            +------------>| Catalog public API |  interface only          |
|                          | contract + DTOs    |                          |
|                          +--------------------+                          |
|                                                                          |
|  +--------------------------------------------------------------------+  |
|  | ONE DATABASE: billing_* | catalog_* | fulfillment_*                |  |
|  | Billing never queries catalog_* directly; it goes via the API      |  |
|  +--------------------------------------------------------------------+  |
+--------------------------------------------------------------------------+

A Laravel modular monolith: one deployable app split into Billing, Catalog and Fulfillment modules that each own their code and tables, with Billing reaching Catalog only through Catalog's public interface.

How do you identify bounded contexts in an existing Laravel codebase?

Start with business capabilities, not with the app/ directory tree. List what the business does, such as selling, shipping, invoicing and supporting customers. Then map controllers, jobs, models and tables to those capabilities. Folder names in a typical Laravel app reflect framework layers, so they tell you little about where the real seams are.

Next, listen to the language each area uses. A boundary often sits where one word changes meaning:

Term In Catalog In Fulfillment
Product Title, description, price, images SKU, weight, dimensions, bin location
Available Visible and purchasable Physically in stock at a warehouse
Variant A selectable option for the customer A separate stock-keeping unit

If one Eloquent model has to serve both meanings, it ends up with nullable columns and conditional logic. That strain points to a hidden boundary.

God models are the strongest signal. A User or Order model with dozens of relationships, and a table that every feature writes to, usually means several contexts share one representation. Each context needs only a slice of it.

Do not split too early or too finely. If an area's rules change every sprint, a boundary you draw now will probably be in the wrong place. You would then maintain interfaces and mapping code that protect nothing. Leave that area as one module until its language settles.

Some concepts really are universal, such as tenant identity or money. Put these in a small shared kernel. Keep it from becoming a dumping ground with three rules:

  • Value objects only. No Eloquent models and no services.
  • Explicit agreement. Every addition needs sign-off from all consuming modules.
  • No conditional logic. Reject anything whose behaviour depends on which context calls it.

How do you structure Laravel modules: directories, namespaces and service providers

Create a top-level modules/ directory with one folder per bounded context, such as modules/Billing, modules/Catalog and modules/Fulfilment. In composer.json, map each one to its own PSR-4 namespace (Billing\\ to modules/Billing/src/). A separate namespace per context makes a cross-context import visible in every use statement, and that is what lets tooling check boundaries later.

Each module owns everything its context needs: domain code, controllers and form requests, jobs, listeners, migrations, config, routes, views, translations and tests. If you delete the folder, the context is gone.

The module service provider as composition root

Each module has one service provider that wires the module into the framework:

  • In register, it binds interfaces to implementations and calls mergeConfigFrom, so the module's defaults apply even when the application has no published config file.
  • In boot, it calls loadRoutesFrom, loadMigrationsFrom, loadViewsFrom and loadTranslationsFrom. The view and translation calls take a namespace, such as billing::invoice, so names cannot collide across modules.

Register every module provider in the application's provider list. Do not rely on discovery for this. One list makes it easy to see what is loaded and in what order.

Where this fights Laravel conventions

Several parts of Laravel assume a single App\ namespace:

  • Package auto-discovery reads the metadata of installed packages, not your path-mapped folders, so module providers are not discovered automatically.
  • Artisan make:* generators write files to app/ by default, so you have to move generated classes into the module or wrap the generators.
  • Third-party packages often default to classes such as App\Models\User, which means you have to override their config.
  • New team members will look in app/ first, so a short README in each module that explains the layout saves time.
<?php
// modules/Billing/src/BillingServiceProvider.php (composer.json maps "Billing\\" => "modules/Billing/src/")

namespace Billing;

use Billing\Contracts\InvoiceRepository;
use Billing\Infrastructure\EloquentInvoiceRepository;
use Illuminate\Support\ServiceProvider;

class BillingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Composition root: bind this context's interfaces to its implementations.
        $this->app->bind(InvoiceRepository::class, EloquentInvoiceRepository::class);

        // Module defaults apply even when config/billing.php was never published.
        $this->mergeConfigFrom(__DIR__.'/../config/billing.php', 'billing');
    }

    public function boot(): void
    {
        $this->loadRoutesFrom(__DIR__.'/../routes/web.php');
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');

        // Namespaced so names cannot collide: view('billing::invoice'), __('billing::messages.paid')
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'billing');
        $this->loadTranslationsFrom(__DIR__.'/../lang', 'billing');
    }
}

// bootstrap/providers.php: one explicit list, in load order, no discovery.
// return [
//     App\Providers\AppServiceProvider::class,
//     Billing\BillingServiceProvider::class,
//     Catalog\CatalogServiceProvider::class,
//     Fulfilment\FulfilmentServiceProvider::class,
// ];

A PHP service provider for the Billing module that binds its interfaces, merges config, loads routes, migrations and namespaced views and translations, and is registered in one central provider list.

How should modules communicate and share data without coupling?

Treat each module's public API as a small, deliberate surface: interfaces bound in the module's service provider, service classes that implement them, and DTOs for input and output. Eloquent models, repositories, scopes and internal jobs stay private. Once a model crosses the boundary, consumers can lazy-load relations, call save() and depend on column names, and the owning module can no longer change its schema safely.

Mechanism Use for Payload Main risk
Synchronous call through a contract Queries and commands that need an answer now DTOs Temporal coupling, long call chains
Event or queued listener Side effects such as notifications, projections and audit IDs and scalars, never models Hidden flows, ordering, retries

Each module owns its tables. Avoid cross-module joins and avoid belongsTo relationships that point into another module. Store the foreign ID and resolve it through the other module's contract. When reads are hot, keep a read model or a denormalized copy that events update.

This approach has real costs. You lose with() eager loading across modules. Reporting and admin screens that used a single join now need batched contract calls or a dedicated read model. Behaviour that runs through events is harder to trace, so document who listens to what. You also have to design ordering, idempotency and failure handling explicitly.

In-process events can give you false confidence. A synchronous listener runs inside the caller's database transaction, so the flow looks atomic. A queued listener can be dispatched before that transaction commits unless you configure it to run after commit. If you later move a module out of the process, the shared transaction disappears entirely. Design for eventual consistency from the start.

<?php
// PHP 8.2+. Several module files are shown together; each comment names the file.

// Modules/Billing/Contracts/InvoiceLookup.php: public contract, bound in BillingServiceProvider
interface InvoiceLookup
{
    public function findForOrder(int $orderId): ?InvoiceSummary;
}

// Modules/Billing/Contracts/InvoiceSummary.php: output DTO, so no Eloquent model crosses the boundary
final readonly class InvoiceSummary
{
    public function __construct(
        public int $invoiceId,
        public int $orderId,
        public int $totalCents,
        public string $status,
    ) {}
}

// Modules/Orders/Events/OrderPlaced.php: payload is IDs and scalars, never an Order model
final readonly class OrderPlaced
{
    public function __construct(public int $orderId, public int $customerId, public int $totalCents) {}
}

// Modules/Billing/Listeners/CreateInvoiceForOrder.php
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
use Illuminate\Contracts\Queue\ShouldQueue;

// Queued, and it runs only after the Orders transaction commits, so it never sees an uncommitted order
final class CreateInvoiceForOrder implements ShouldQueue, ShouldHandleEventsAfterCommit
{
    public function handle(OrderPlaced $event): void
    {
        // Invoice is Billing's private model. A unique index on order_id plus firstOrCreate
        // keeps queue retries from creating a duplicate invoice.
        Invoice::firstOrCreate(['order_id' => $event->orderId], ['total_cents' => $event->totalCents]);
    }
}

This PHP sketch shows a module's public contract and DTO, an event that carries only scalars, and a queued, idempotent listener in the owning module that runs only after the dispatching transaction commits.

How do you enforce module boundaries in tests and CI?

Boundaries that exist only in a README do not survive a deadline. When a ticket is due and the Billing code needs an order total, the quickest fix is to import Modules\Orders\Models\Order and query it directly. Code review may catch it once, but not every time. Each shortcut makes the next one look acceptable. Within a few months the "modules" are folders inside a monolith that is just as tangled as before. Enforcement has to be automatic and has to block merges.

Architecture tests in the existing suite

Pest's arch testing lets you state dependency rules as ordinary tests. For each module, assert that its namespace does not use any other module's internal namespaces, such as models, repositories and jobs. Allow only the public contracts and events. Because these run with the rest of the suite, a violation fails the same CI job that runs unit tests, and nobody has to remember a separate step. If you prefer static analysis, Deptrac expresses the same rules as layers and allowed dependencies, and it exits non-zero on violations. Pick one tool. Running two rule sets invites drift.

Testing strategy per module

  • Unit and feature tests live inside the module. They exercise its own HTTP routes, jobs and domain logic.
  • Other modules' contracts are faked at the boundary. Bind a fake implementation of OrderQueryContract in the container, or use Event::fake() to assert on dispatched events. These tests then break only when your own module changes.
  • A small set of end-to-end tests covers critical cross-module flows, such as checkout through invoicing. They catch contract mismatches that fakes hide. Keep the set small, because these tests are slow and brittle.
# deptrac.yaml: dependency rules between modules.
# CI runs `vendor/bin/deptrac analyse`, which exits non-zero on any violation,
# so a forbidden import blocks the merge.
deptrac:
  paths:
    - ./Modules
  layers:
    # Public surface of Orders: contracts and events other modules may use.
    - name: OrdersPublic
      collectors:
        - type: directory
          value: Modules/Orders/(Contracts|Events)/.*
    # Everything else in Orders (models, repositories, jobs) is internal.
    - name: OrdersInternal
      collectors:
        - type: directory
          value: Modules/Orders/(?!Contracts/|Events/).*
    - name: BillingPublic
      collectors:
        - type: directory
          value: Modules/Billing/(Contracts|Events)/.*
    - name: BillingInternal
      collectors:
        - type: directory
          value: Modules/Billing/(?!Contracts/|Events/).*
  ruleset:
    # A module's internals may use their own public surface and other
    # modules' public surfaces. They may never use another module's internals.
    OrdersInternal:
      - OrdersPublic
      - BillingPublic
    BillingInternal:
      - BillingPublic
      - OrdersPublic
    # Contracts and events stay self-contained, so the public API cannot
    # leak internal types.
    OrdersPublic: ~
    BillingPublic: ~

A Deptrac configuration that splits each module into a public layer (contracts and events) and an internal layer, then allows dependencies only on other modules' public layers, so vendor/bin/deptrac analyse fails CI when Billing imports Modules\Orders\Models\Order.

How do you migrate a large Laravel app to modules incrementally?

Treat the migration as a strangler, not a rewrite. A big-bang restructure stalls feature work and produces a diff too large to review. Extracting one context at a time keeps the application shippable after every step.

Start with the most isolated context

Pick the context with the fewest inbound dependencies, such as notifications, reporting or a self-contained third-party integration. A low-risk first extraction lets the team settle conventions (provider layout, contract naming, test setup) before touching central areas like orders or billing, where mistakes are expensive.

Contract first, files second

Define the module's public interface and route existing callers through it while the implementation still lives in app/. This step changes how callers reach the code but not where it lives, so it is easy to review and test. Once nothing depends on internals, moving the files into the module becomes a mechanical namespace change.

Then take ownership of tables

Make the module the only writer to its tables. Replace outside queries with contract calls or events. Then add the boundary checks described earlier so the separation cannot quietly erode.

Living with the hybrid

app/ and module directories will coexist for a long time. Set one rule: new code for an extracted context goes in its module, and code that remains in app/ may call a module only through its contract.

Expect each feature to cost more at first, because it needs a contract, an event or a provider binding. That ceremony pays off later through less coordination between teams and fewer cases where a change in one area silently breaks another.

When should you avoid modules, and what are the alternatives?

That ceremony is only worth paying for when there is something to protect. Skip modules in small apps that a few developers can hold in their heads, because boundaries add indirection without reducing coordination. Skip them in early-stage products whose domain is still shifting. Contexts drawn too early lock in the wrong seams, and merging two modules is harder than splitting one later. Skip them if the team will not maintain the architecture tests and CI checks. Unenforced boundaries decay into a conventional app with extra folders.

Approach Deployment Scaling Fault isolation Team coordination Operational cost
Conventional Laravel layout One unit Whole app None High once teams grow Lowest
Technical-layer layout (Domain/, Infrastructure/ across all features) One unit Whole app None High: every feature touches every layer Low
Modular monolith by bounded context One unit Whole app, queues per module Code-level only Lower: owners per context Low to moderate
Microservices Per service Per service Process and network Lowest day to day, but contract changes need negotiation Highest

A modular monolith only isolates code. One database and one deployment are still a shared failure and scaling domain. A slow migration, a runaway query or a bad release affects every module.

A module is ready to become a service when it has a distinct scaling profile, availability need or release cadence that the shared deployment blocks. Extraction is cheap only if the module already exposes clean contracts, owns its tables outright, and integrates through events. Once those are in place, extraction mostly means swapping an in-process call for a network call and an event bus for a broker.

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 architecture, 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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.