What is a Laravel modular monolith, and why do folders alone not make one?

A Laravel modular monolith is a single deployable Laravel application divided into modules, where each module corresponds to a bounded context such as Billing, Catalog or Fulfillment. Each module exposes an explicit public contract, typically a small set of interfaces, DTOs and events, and hides everything else. Dependency rules decide which modules may depend on which, and those rules are checked rather than assumed.

This article's thesis is that folder structure is the least important part of that definition and boundary enforcement is the most important. Moving controllers and models into Modules/Billing changes nothing if an Orders controller can still query Billing\Models\Invoice directly or eager-load it through a relationship. In that case the folders only make the coupling harder to see. A module exists when crossing its boundary means going through its contract, and when a violation fails a check in CI.

Teams adopt the pattern to contain coupling as a codebase and its team grow. When dependencies point in known directions, a change to Billing internals has a predictable blast radius, and new engineers can reason about one context without loading the whole system. It also keeps extraction possible. A module that already talks to others only through a contract can later become a separate service with far less untangling.

Be clear about what the pattern does not give you. There is still one deployment, one runtime and usually one database. A memory leak in one module affects all of them, a slow migration blocks every release, and you cannot scale Catalog separately from Billing. Modules buy you organizational and code-level isolation. They do not buy operational isolation.

How do you identify bounded contexts before touching code?

Start with language, not directories. Talk to the people who run each workflow and listen for nouns that change meaning depending on who says them. In Billing, a Customer is a legal entity with a tax ID, payment methods and an invoice history. In Support, a Customer is a person with open tickets, a preferred contact channel and an SLA tier. If one Customer model serves both, it gathers nullable columns and if branches for each audience. If each context owns its own Customer and the two link by an ID, both models stay small and accurate.

Next, map change. Note which team owns which workflow, and check version control history to see which files change together in the same pull requests. Code that changes for the same business reason belongs in the same module.

Split by What a typical feature touches Result
Technical layer (Controllers, Models, Services) Every layer Every change crosses every module
Database table Several tables per workflow Modules become CRUD wrappers, and the real logic ends up in their callers
Bounded context One workflow and its data Most changes stay inside one module

Take extra time here, because a wrong boundary gets more expensive the longer it stays. It produces constant calls between modules, then shared transactions. Eventually you have to merge or re-split, which means moving table ownership and migrating data while the system is live.

Signs a proposed boundary is wrong:

  • Routine features need coordinated changes in two modules.
  • One module reads another module's tables directly.
  • A single use case needs a transaction that spans modules.
  • One team owns several modules, or several teams share one.

How does a Laravel module work? Domain structure and the service provider as composition root

Put each context under a top-level modules/ directory, for example modules/Billing and modules/Catalog. Give each one its own namespace and register it as a PSR-4 entry in composer.json. A separate namespace root makes ownership show up in every use statement, and it gives static analysis a clean prefix to check later.

Inside a module, split the code into three areas:

  • Domain holds entities, value objects, domain events and the interfaces the module depends on, such as InvoiceRepository. It should not import framework HTTP or persistence classes, so business rules stay testable and readable without the framework in the way.
  • Application holds use cases: one class per action, like IssueInvoice. These orchestrate domain objects and define the module's public entry points.
  • Infrastructure/Http holds Eloquent implementations, controllers, form requests, routes, migrations and views. This is everything that touches I/O.

Each module ships a service provider that acts as its composition root. It binds domain interfaces to their infrastructure implementations in the container. It calls loadRoutesFrom, loadMigrationsFrom and loadViewsFrom, and it uses mergeConfigFrom for module config. The application only registers the provider in its provider list and never learns where a module's routes or tables live. Removing or extracting a module then mostly means removing one provider.

The three-way split pays off for contexts with real rules. A small, CRUD-heavy context, like an admin lookup table, can use a flat folder with models, controllers and a provider. The layering would only add indirection there.

Expect friction with tooling. make:* generators write to app/ by default. Package auto-discovery only covers Composer packages, not in-repo modules. IDE plugins and some test configurations also assume the default layout and may need path configuration.

<?php
// modules/Billing/BillingServiceProvider.php
// composer.json autoload.psr-4: "Modules\\Billing\\": "modules/Billing/"
// The app only lists this class in its providers. It learns nothing else about Billing.

namespace Modules\Billing;

use Illuminate\Support\ServiceProvider;
use Modules\Billing\Domain\InvoiceRepository;
use Modules\Billing\Infrastructure\Persistence\EloquentInvoiceRepository;

class BillingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Composition root: the domain interface is resolved to its Eloquent implementation here only.
        $this->app->bind(InvoiceRepository::class, EloquentInvoiceRepository::class);

        // Module defaults live under the 'billing' key. An app-level config/billing.php overrides them.
        $this->mergeConfigFrom(__DIR__.'/config/billing.php', 'billing');
    }

    public function boot(): void
    {
        // Routes, tables and templates stay inside the module directory.
        $this->loadRoutesFrom(__DIR__.'/Infrastructure/Http/routes.php');
        $this->loadMigrationsFrom(__DIR__.'/Infrastructure/Database/migrations');

        // Namespaced views, referenced as view('billing::invoices.show').
        $this->loadViewsFrom(__DIR__.'/Infrastructure/Http/views', 'billing');
    }
}

A Billing module's service provider acts as the module's composition root: it binds the domain repository interface, merges the module's config, and loads the module's own routes, migrations and namespaced views (PHP code).

How should modules talk to each other without leaking internals?

Each module exposes a small public surface: interfaces under a Contracts namespace, DTOs or value objects for data crossing the boundary, and domain events describing facts that already happened. Eloquent models, repositories and internal services stay private. If Billing calls Orders\Models\Order::find() and reads $order->lines, Billing now depends on Orders' table shape, casts and lazy-loading behaviour. If Billing calls OrderLookup::summaryFor($orderId) and receives an OrderSummary DTO, Orders can restructure its storage without breaking callers. The example below shows both versions side by side.

Synchronous contract call Asynchronous event + queued listener
Consistency Immediate, can share a transaction Eventual
Failure Caller sees the exception Retries, failed jobs
Coupling Caller knows the provider Publisher ignores consumers
Debugging Single stack trace Spread across workers and logs

Use contracts when the caller needs an answer now. Use events when other modules only need to react.

Timing matters with events. A listener that runs inside the transaction can act on data that is later rolled back. A queued job can also start before the commit and fail to find the row. Dispatch after commit, either through DB::afterCommit or the after-commit settings on queued listeners.

Queues deliver at least once, so listeners must be idempotent. Key side effects on the event ID or use a unique constraint.

Events also bring ordering problems, duplicate delivery and flows that are hard to trace. Because everything runs in one codebase, teams tend to underestimate these costs. The contracts, DTOs and mappers also add files and ceremony. Keep the public surface small so that this overhead stays proportionate.

<?php // PHP. Billing module (consumer) and Orders module (provider)

// LEAKY: Billing depends on Orders' table shape, relations and casts.
$order = \App\Modules\Orders\Models\Order::with('lines')->findOrFail($orderId);
$totalCents = $order->lines->sum(fn ($line) => $line->unit_price_cents * $line->qty);

// CONTRACT: Billing sees only Orders' public API (interface + DTO).
$summary = app(\App\Modules\Orders\Contracts\OrderLookup::class)->summaryFor($orderId);
$totalCents = $summary->totalCents; // Orders can change storage freely

// Orders/Contracts: the whole public surface Billing is allowed to touch.
interface OrderLookup { public function summaryFor(string $orderId): OrderSummary; }
final class OrderSummary {
    public function __construct(public readonly string $orderId, public readonly int $totalCents) {}
}
final class OrderPlaced { // domain event: a fact, carrying IDs, not models
    use \Illuminate\Foundation\Events\Dispatchable;
    public function __construct(public readonly string $eventId, public readonly string $orderId) {}
}

// Orders publishes the event inside its own transaction.
DB::transaction(function () use ($order) {
    $order->save();
    OrderPlaced::dispatch((string) Str::uuid(), $order->id);
});

// Billing reacts asynchronously.
final class CreateInvoiceForPlacedOrder implements \Illuminate\Contracts\Queue\ShouldQueue {
    public bool $afterCommit = true; // queue only after Orders commits; skipped on rollback
    public function __construct(private OrderLookup $orders) {}
    public function handle(OrderPlaced $event): void {
        $summary = $this->orders->summaryFor($event->orderId);
        // At-least-once delivery: a unique index on invoices.source_event_id
        // turns a redelivered event into a no-op instead of a second invoice.
        Invoice::firstOrCreate(['source_event_id' => $event->eventId],
            ['order_id' => $summary->orderId, 'amount_cents' => $summary->totalCents]);
    }
}

Billing reading Orders' Eloquent model directly versus calling its OrderLookup contract, plus a queued listener that runs after commit and uses the event ID to stay idempotent.

How do you handle Eloquent relationships, foreign keys and table ownership across contexts?

A belongsTo from Billing\Invoice to Accounts\Customer looks harmless, but it couples Billing to Accounts' model class, table name and column layout. Every with('customer') and whereHas is a query against a table that Billing does not own. As these calls accumulate, the boundary drawn in the folder structure no longer exists in the data layer.

Each module should own its tables, and the ownership should be visible in the names. Use a prefix such as billing_invoices or, on PostgreSQL, one schema per module. No other module queries those tables, whether through Eloquent, the query builder or raw SQL. That rule is what keeps extraction possible. If only Billing reads billing_*, you can move those tables to another database by changing a single module.

Option How it works Fits when Cost
ID-only reference Store customer_id and resolve it through the owning module's contract Most cross-context links No eager loading or joins, and more queries
Consumer-owned read model Billing keeps its own billing_customer_snapshots table, updated from Accounts events Hot read paths and listings Hand-written projections and eventual consistency
Shared kernel A small, jointly owned module holding a concept such as Money or CountryCode Concepts that are identical in every context Tends to become a dumping ground

Cross-module reporting needs a sanctioned exception, such as a dedicated reporting module with read-only access or a separate replica, so that analysts' joins do not slowly turn into application code. A shared kernel needs written entry criteria before it gets any code. For example: the concept has no lifecycle, has no owner, and every context means the same thing by it.

-- PostgreSQL: one schema per module makes table ownership visible.
CREATE SCHEMA accounts;
CREATE SCHEMA billing;

CREATE TABLE accounts.customers (
    id         uuid PRIMARY KEY,
    name       text NOT NULL,
    country    char(2) NOT NULL
);

-- ID-only reference: customer_id has no FOREIGN KEY to accounts.customers.
-- Billing resolves it through the Accounts module's contract.
CREATE TABLE billing.invoices (
    id           uuid PRIMARY KEY,
    customer_id  uuid NOT NULL,
    total_cents  bigint NOT NULL,
    currency     char(3) NOT NULL
);

-- Consumer-owned read model, written only by Billing's listeners for Accounts events.
CREATE TABLE billing.customer_snapshots (
    customer_id  uuid PRIMARY KEY,
    name         text NOT NULL,
    updated_at   timestamptz NOT NULL
);

-- Each module connects with its own role and can only reach its own schema.
CREATE ROLE billing_app LOGIN PASSWORD 'change-me-billing';
GRANT USAGE ON SCHEMA billing TO billing_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA billing TO billing_app;

-- Sanctioned exception: a read-only reporting role that may join across schemas.
CREATE ROLE reporting_ro LOGIN PASSWORD 'change-me-reporting';
GRANT USAGE ON SCHEMA accounts, billing TO reporting_ro;
GRANT SELECT ON ALL TABLES IN SCHEMA accounts, billing TO reporting_ro;

A PostgreSQL setup in which each module owns a schema. Billing stores customers as ID-only references with no cross-schema foreign key and keeps its own snapshot table, while only a read-only reporting role is allowed to join across modules.

How do you enforce module boundaries automatically?

Boundaries that exist only as convention erode under deadline pressure. A developer reaches into Billing\Internal\InvoiceCalculator from Orders to ship a fix by Friday, nobody notices, and six months later you have a distributed monolith in one repo: all the old coupling, plus the folder overhead.

Three mechanisms keep boundaries from eroding:

  • Architecture tests in your existing suite. For each module, the test collects every PHP file under its directory, extracts the use statements, and fails if any import points into another module's namespace outside that module's Contracts or Events namespace. The example below does this with plain PHPUnit or Pest and needs no extra package.
  • Static analysis rules that apply the same constraint and report the exact file and line. They also catch fully qualified class references written inline, which a use-statement scan misses.
  • Code-review ownership per module directory, so changes to Billing/ need approval from the team that owns billing.

The testing strategy follows the same lines. Unit tests cover domain logic with no framework boot. Module-level feature tests enter only through the public contract, the same way other modules do. Other modules' contracts are bound to fakes in the container, so a Shipping test never needs to seed Billing data and never breaks when Billing changes its schema.

Each of these fails the build at the moment someone introduces a coupling, while the change is still small and the author still remembers why they made it. That costs minutes. Untangling the same dependency months later, after other code has been built on top of it, means a refactor across several teams.

<?php
// tests/Architecture/ModuleBoundaryTest.php (plain PHPUnit, no extra packages)
namespace Tests\Architecture;

use PHPUnit\Framework\TestCase;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

final class ModuleBoundaryTest extends TestCase
{
    // Assumes modules live in app/Modules/{Name} under namespace App\Modules\{Name}
    private const MODULES_DIR = __DIR__ . '/../../app/Modules';
    // The only namespaces another module is allowed to import
    private const PUBLIC_AREAS = ['Contracts', 'Events'];

    public function test_modules_only_import_other_modules_public_api(): void
    {
        $violations = [];
        foreach (glob(self::MODULES_DIR . '/*', GLOB_ONLYDIR) as $moduleDir) {
            $module = basename($moduleDir);
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($moduleDir, RecursiveDirectoryIterator::SKIP_DOTS));
            foreach ($files as $file) {
                if ($file->getExtension() !== 'php') { continue; }
                // Captures top-level imports such as "use App\Modules\Billing\Internal\InvoiceCalculator;"
                // Inline FQCNs and grouped imports are left to static analysis.
                preg_match_all('/^use\s+App\\\\Modules\\\\(\w+)\\\\(\w+)[^;]*;/m', file_get_contents($file->getPathname()), $matches, PREG_SET_ORDER);
                foreach ($matches as [$statement, $targetModule, $area]) {
                    $isOwnModule = $targetModule === $module;
                    $isPublicApi = in_array($area, self::PUBLIC_AREAS, true);
                    if (!$isOwnModule && !$isPublicApi) {
                        $violations[] = "{$file->getPathname()}: {$statement}";
                    }
                }
            }
        }
        // An empty list passes. Otherwise the failure lists each offending file and import.
        $this->assertSame([], $violations, "Cross-module imports of internals:\n" . implode("\n", $violations));
    }
}

A dependency-free PHPUnit architecture test that scans each module's top-level use statements and fails CI when a module imports another module's namespace outside its Contracts or Events namespace.

When should you adopt a modular monolith, when should you avoid it, and what are the alternatives?

A modular monolith pays off when several teams work in one large Laravel app and the domains are clearly distinct: billing, catalog, fulfilment. In that setting, the main cost is coordination. Each team needs to know who may change what, and the module boundaries answer that question in code rather than in meetings. You pay upfront in contracts, service provider wiring and the effort of designing boundaries. You get that back later, because changes to one module stop rippling into the others.

Avoid it for small apps and for CRUD-heavy areas such as admin panels or settings screens. There, a contract wrapping a single Eloquent call is ceremony that hides the code without protecting anything. Also avoid it if a team genuinely needs independent scaling or deployment. A modular monolith still ships as one artifact.

Approach Boundary enforcement Deployment Main cost
Default app/ with conventions Code review only Single Boundaries erode quietly
Modular monolith Static analysis and architecture tests Single Upfront design and wiring
Package-based modules Composer dependencies Single Versioning and release overhead
Microservices Network Independent Operations, distributed failures

Migrating an existing app

  1. Pick one context whose boundaries the team already agrees on.
  2. Define its contract.
  3. Route existing callers through the contract while the implementation stays where it is.
  4. Move the code behind the contract.
  5. Turn on the enforcement rule for that module.
  6. Repeat with the next context.

Each step leaves the app working, and you can stop at any point. A big-bang reorganization freezes feature work, produces a diff nobody can review properly, and fixes boundaries in place before you have learned where they actually belong.

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.