A Modular Monolith in Laravel: Boundaries Before Microservices

11 min read

Most Laravel applications start as one application because they should. One deployment, one database, one queue and one debugger make a new product easier to understand and cheaper to change. The trouble starts with the accidental monolith: app/Services becomes a drawer for unrelated behaviour, any controller can query any model, and a change in billing quietly reaches into fulfilment.

A modular monolith keeps the operational simplicity of one Laravel application and makes business boundaries explicit in code, so that extracting a service later is possible but not required up front.

This article uses a B2B ordering application with Catalog, Orders, Billing and Fulfilment. We will place code by module, make dependencies point in one direction, enforce that rule in CI, and decide what deserves the small shared kernel.

Begin with a business boundary, not a technical layer

The familiar Laravel layout is convenient at first:

text
app/
  Http/Controllers/
  Models/
  Services/
  Jobs/

It groups classes by framework role, not by the reason the business changes. Creating an order can touch a controller, request, model, service, event and job in six directories. A developer who needs to change the order flow has to know the whole application before they can find it.

A module-first layout keeps a use case close to its collaborators:

text
app/
  Modules/
    Catalog/
      Application/
      Domain/
      Infrastructure/
      Http/
    Orders/
      Application/
      Domain/
      Infrastructure/
      Http/
    Billing/
      Application/
      Domain/
      Infrastructure/
  Shared/
    Domain/
    Infrastructure/

Do not read this as a mandate for four layers everywhere. The names make two questions visible: which module owns this rule, and which dependency crosses a module boundary? Eloquent models such as Order sit in Infrastructure because they are persistence adapters, while Domain holds events and business rules. A small module can have only Application and Http; introduce Domain or Infrastructure when it contains a real concept or an adapter that benefits from a boundary.

Give each module a public application surface

Orders owns the act of placing an order. A controller should depend on that action, not on Order, Product, StockItem and an event from three other modules. The input becomes a small immutable contract.

php
<?php

declare(strict_types=1);

namespace App\Modules\Orders\Application;

final readonly class PlaceOrderData
{
    /** @param list<PlaceOrderLineData> $lines */
    public function __construct(
        public int $customerId,
        public array $lines,
    ) {
        if ($lines === []) {
            throw new \InvalidArgumentException('An order requires at least one line.');
        }
    }
}

final readonly class PlaceOrderLineData
{
    public function __construct(
        public int $productId,
        public int $quantity,
    ) {
        if ($quantity < 1) {
            throw new \InvalidArgumentException('Quantity must be positive.');
        }
    }
}

The HTTP adapter translates validated request data into that contract. It does not become the order workflow.

php
<?php

declare(strict_types=1);

namespace App\Modules\Orders\Http;

use App\Http\Controllers\Controller;
use App\Modules\Orders\Application\PlaceOrder;
use App\Modules\Orders\Application\PlaceOrderData;
use App\Modules\Orders\Application\PlaceOrderLineData;
use Illuminate\Http\RedirectResponse;

final class PlaceOrderController extends Controller
{
    public function __construct(
        private readonly PlaceOrder $placeOrder,
    ) {}

    public function __invoke(PlaceOrderRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        $order = $this->placeOrder->handle(new PlaceOrderData(
            customerId: $validated['customer_id'],
            lines: array_map(
                fn (array $line): PlaceOrderLineData => new PlaceOrderLineData(
                    productId: $line['product_id'],
                    quantity: $line['quantity'],
                ),
                $validated['lines'],
            ),
        ));

        return to_route('orders.show', $order);
    }
}

The controller may live in the module while routes stay in routes/web.php. Only the dependency direction matters; there is no need to move every Laravel convention into a new folder.

Depend on another module's contract, never its tables

Orders needs to reserve stock from Catalog. Importing Catalog's Eloquent model is tempting, but it makes the order flow depend on catalog persistence and encourages direct updates to another module's data. Instead, Catalog publishes an application contract that describes the capability Orders needs.

php
<?php

declare(strict_types=1);

namespace App\Modules\Catalog\Application;

interface StockReservation
{
    public function reserve(int $productId, int $quantity, string $reference): void;
}

The Order action receives that capability, owns its transaction, and publishes a business fact after the write commits. The action is allowed to use its own Eloquent models; it is not allowed to reach into Catalog's models.

php
<?php

declare(strict_types=1);

namespace App\Modules\Orders\Application;

use App\Modules\Catalog\Application\StockReservation;
use App\Modules\Orders\Domain\OrderPlaced;
use App\Modules\Orders\Infrastructure\Order;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Facades\DB;

final class PlaceOrder
{
    public function __construct(
        private readonly StockReservation $stockReservation,
        private readonly Dispatcher $events,
    ) {}

    public function handle(PlaceOrderData $data): Order
    {
        return DB::transaction(function () use ($data): Order {
            $order = Order::query()->create([
                'customer_id' => $data->customerId,
                'status' => 'pending',
            ]);

            foreach ($data->lines as $line) {
                $this->stockReservation->reserve(
                    productId: $line->productId,
                    quantity: $line->quantity,
                    reference: (string) $order->getKey(),
                );

                $order->lines()->create([
                    'product_id' => $line->productId,
                    'quantity' => $line->quantity,
                ]);
            }

            $this->events->dispatch(new OrderPlaced(orderId: $order->getKey()));

            return $order;
        });
    }
}

In production, a transaction alone does not guarantee delivery to an asynchronous consumer. Use an outbox record or a ShouldDispatchAfterCommit event when the side effect must not see a rolled-back order. Events communicate a completed fact; direct cross-module calls create a synchronous dependency.

php
<?php

declare(strict_types=1);

namespace App\Modules\Orders\Domain;

use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;

final readonly class OrderPlaced implements ShouldDispatchAfterCommit
{
    public function __construct(public int $orderId) {}
}

Billing can now listen to OrderPlaced and create an invoice without Orders knowing whether an invoice exists. Do not dispatch an event just to avoid a normal return value: when a caller needs an answer immediately, an explicit application contract is clearer.

Keep the shared kernel deliberately small

Shared is the part most modular monoliths get wrong. It starts as a home for real cross-cutting abstractions and ends as app/Shared/Everything. Treat it as a kernel with a high admission bar.

A currency value object, an actor identifier or a generic clock can belong there if several modules genuinely share the same meaning and lifecycle. An OrderStatus, CatalogProduct or InvoiceNumber does not: moving it to Shared merely hides ownership.

php
<?php

declare(strict_types=1);

namespace App\Shared\Domain;

final readonly class Money
{
    public function __construct(
        public int $amountInMinorUnits,
        public string $currency,
    ) {
        if ($amountInMinorUnits < 0) {
            throw new \InvalidArgumentException('Money cannot be negative.');
        }

        if (preg_match('/^[A-Z]{3}$/', $currency) !== 1) {
            throw new \InvalidArgumentException('Currency must be a three-letter ISO code.');
        }
    }
}

The test: can Catalog, Orders and Billing use this object without one of them waiting on another module's business change? If not, duplicate the small type locally. A little duplication is cheaper than a false common dependency.

Make the boundary executable

Folder names are a convention. A convention without a test becomes optional during a busy release. Deptrac can assert architectural layers and module access in CI. The exact configuration should reflect your namespaces; this version states the important rule: a module may use itself, Shared and another module's published contracts, but not that module's Infrastructure or Http code. In this example Catalog\Application holds only published contracts, so it gets a layer of its own.

yaml
deptrac:
  paths:
    - ./app
  layers:
    - name: Orders
      collectors:
        - type: directory
          value: app/Modules/Orders/.*
    - name: CatalogContracts
      collectors:
        - type: directory
          value: app/Modules/Catalog/Application/.*
    - name: Catalog
      collectors:
        - type: bool
          must:
            - type: directory
              value: app/Modules/Catalog/.*
          must_not:
            - type: directory
              value: app/Modules/Catalog/Application/.*
    - name: Shared
      collectors:
        - type: directory
          value: app/Shared/.*
    - name: Laravel
      collectors:
        - type: classLike
          value: Illuminate\\.*
  ruleset:
    Orders:
      - CatalogContracts
      - Shared
      - Laravel
    Catalog:
      - CatalogContracts
      - Shared
      - Laravel
    CatalogContracts:
      - Shared
      - Laravel
    Shared:
      - Laravel

Orders is allowed to use CatalogContracts but not Catalog, so the import of StockReservation passes while a use of Catalog's Eloquent models or controllers fails the build. The bool collector keeps the contracts out of the Catalog layer; without must_not, the same class would belong to both layers and still be reported against the stricter one. Do not weaken every boundary merely to make one dependency pass.

PHP architecture tests are another useful line of defence because they run with the test suite and fail in familiar output.

php
<?php

declare(strict_types=1);

arch('orders do not use catalog infrastructure')
    ->expect('App\\Modules\\Orders')
    ->not->toUse('App\\Modules\\Catalog\\Infrastructure');

arch('other modules do not use the catalog HTTP layer')
    ->expect('App\\Modules\\Orders')
    ->not->toUse('App\\Modules\\Catalog\\Http');

arch('billing does not use the catalog HTTP layer')
    ->expect('App\\Modules\\Billing')
    ->not->toUse('App\\Modules\\Catalog\\Http');

Each rule names the module whose code is checked, so Catalog's own HTTP classes are not flagged for using each other. Neither tool judges the design; they only check an agreed one on every build. Start with two or three high-value rules and tighten them as existing violations are removed; a thousand ignored exceptions are worse than no rule.

Test behaviour at the module edge

The public action is a natural feature-test seam. A test should prove the business outcome and the module interaction, not assert private method calls.

php
<?php

declare(strict_types=1);

use App\Models\Customer;
use App\Modules\Catalog\Application\StockReservation;
use App\Modules\Catalog\Infrastructure\Product;
use App\Modules\Orders\Application\PlaceOrder;
use App\Modules\Orders\Application\PlaceOrderData;
use App\Modules\Orders\Application\PlaceOrderLineData;
use App\Modules\Orders\Domain\OrderPlaced;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;

uses(RefreshDatabase::class);

final class FakeStockReservation implements StockReservation
{
    /** @var list<array{productId: int, quantity: int, reference: string}> */
    public array $reservations = [];

    public function reserve(int $productId, int $quantity, string $reference): void
    {
        $this->reservations[] = compact('productId', 'quantity', 'reference');
    }
}

it('places an order after catalog reserves stock', function (): void {
    $customer = Customer::factory()->create();
    $product = Product::factory()->create();

    Event::fake([OrderPlaced::class]);

    $reservation = new FakeStockReservation();
    app()->instance(StockReservation::class, $reservation);

    $order = app(PlaceOrder::class)->handle(new PlaceOrderData(
        customerId: $customer->id,
        lines: [new PlaceOrderLineData(productId: $product->id, quantity: 2)],
    ));

    expect($order->status)->toBe('pending');
    expect($reservation->reservations)->toHaveCount(1);
    Event::assertDispatched(
        OrderPlaced::class,
        fn (OrderPlaced $event): bool => $event->orderId === $order->id,
    );
});

The fake isolates one external capability (stock reservation) while the order write stays real. Factories create the customer and product before Event::fake(), as the Laravel documentation advises when events matter to factories, and faking only OrderPlaced leaves Eloquent model events untouched. Contract tests for a published interface pay off once its implementation becomes remote.

When a modular monolith is the better choice

Choose this architecture when the product is still one business system, the same team releases its parts together, and cross-module changes remain common. You gain local reasoning, code ownership and testable seams without duplicating authentication, deployments, observability, queues and data consistency machinery across services.

Modules can share the framework, the container and a database transaction, but the source tree stops pretending every model belongs to everyone.

When not to use it

Do not impose module layers on a small CRUD application with three screens and one team-owned concept. A clear app/Models, Form Request and controller can be the cheaper design. Do not carve a module for every Eloquent model, and do not introduce an event for each setter. Boundaries should follow business change and ownership, not table count.

Likewise, do not call this a modular monolith while allowing all modules to query one another's tables. That is a reorganised big ball of mud. Start with the places where accidental coupling has already caused rework: billing changing order status, reporting reaching through five relationships, or an integration making controller code hard to test.

When to split a service for real

A directory is not a microservice waiting for a Kubernetes cluster. Extract only when a boundary has operational evidence behind it: a different team must deploy independently, a workload needs independent scaling or isolation, regulatory access rules require separate data control, or the failure profile is materially different.

Before extraction, prove the boundary inside the monolith. Give it a contract, prevent database shortcuts, consume its events idempotently, and observe its calls. Then the first extraction replaces an in-process adapter with HTTP, a queue or a database-owned integration, not every class with a network request.

The cost is real: distributed tracing, retries, idempotency, schema evolution, local development and incident response all become harder. A modular monolith is successful when it keeps that cost deferred until the business has earned it.

Common failure modes

The most common failure is a giant Shared folder. Keep ownership visible; promote a type only after repeated, stable cross-module use. The second is synchronous event theatre: dispatching an event and immediately depending on a listener for correctness makes the flow invisible. Use a direct contract for synchronous decisions and events for completed facts.

Another failure is treating Deptrac exemptions as harmless. Every ignored violation documents an unclear dependency. Either make a narrow public contract or remove the rule temporarily; do not pile up baseline debt that nobody reads. Finally, remember that one database transaction is a convenience, not an architectural boundary. If a future service owns its data, its contract and failure modes must already be explicit.

Related articles

Existing system support

Need help with a live application?

I help companies improve live systems, clean up delivery workflows, and ship new features without adding avoidable complexity.

Comments (0)
Sign in to leave a comment

You need to be signed in to add a comment.

Login

Need someone to take responsibility for the next step?

Let’s talk about your project and define a scope that actually makes sense for your goals.