What is a laravel modular structure, and why do large Laravel apps need one?

A laravel modular structure organizes a single deployable application by business domain instead of by technical layer. Rather than one app/Models, one app/Http/Controllers and one app/Services shared by every feature, you get modules such as Billing, Catalog and Identity. Each module owns its models, controllers, jobs, migrations and routes, and each exposes a small, explicit public API: a few service interfaces, DTOs and events that other modules are allowed to use. Everything else is internal. It is still a monolith, with one codebase, one deploy and usually one database. The modularity is in how the code is allowed to depend on itself.

The default Laravel layout works well for small apps. In a large Laravel app, though, it lets any class reach any other class. A checkout controller queries the User model directly, a report job joins billing tables, and a "small" pricing change ripples into a dozen files nobody expected. Folders grouped by type say nothing about who owns what, so every change needs a search through the whole codebase.

The thesis of this guide is that enforced boundaries matter more than the folder layout or the package you pick. Moving files into Modules/Billing changes nothing if Catalog can still import Billing's Eloquent models.

Enforced boundaries pay off most in long-lived codebases with several business capabilities and more than one team. When ownership is clear, a change touches fewer files and needs fewer reviewers. A new engineer can learn one module's public API without reading the rest of the system.

How do you identify module boundaries from business capabilities?

Start from what the business does, not from what Laravel generates. A default app groups code by technical layer: every model in one directory, every controller in another. That tells you nothing about who owns what. Instead, list the capabilities the business would recognize: Billing, Catalog, Fulfillment, Identity. Each one that has its own vocabulary, rules and likely owner is a candidate module. If "account" means a login in one conversation and a ledger entry in another, you have found a boundary.

Signs a boundary is wrong

  • One feature keeps touching several modules. If adding a discount type always needs edits in Catalog, Billing and Checkout, the concept is spread across modules instead of living in one. Merge them, or move the rule to the module that owns the decision.
  • Eloquent models are shared between modules. When Fulfillment queries Billing\Models\Invoice directly, the table schema becomes a public API. Neither module can change it without breaking the other.

Start coarse

Draw fewer, larger modules first and split them once the seams are clear. Merging later is cheap. Moving code out of a module means redefining the contracts other modules depend on and splitting migrations and tables that already hold production data.

Apply domain-driven design selectively. Aggregates, repositories and value objects used everywhere work against Eloquent's active-record model, where the model already is the persistence layer. Keep them for the few areas with complex invariants, such as pricing or ledger rules. Plain Eloquent is fine for the rest.

How does a Laravel module work? Directory layout and self-registering providers

A practical layout puts a top-level modules/ directory next to app/, with one folder per domain: modules/Billing, modules/Catalog, modules/Fulfillment. Each module holds its own routes/, database/migrations/, config/, Providers/, Models/, Actions/, Jobs/ and tests/. Deleting or extracting a domain then means moving one folder, not searching a dozen shared directories for its files.

Composer handles class loading. Add a PSR-4 entry to the autoload section of composer.json that maps the Modules\ namespace to modules/, then run composer dump-autoload. Modules\Billing\Actions\IssueInvoice then resolves to modules/Billing/Actions/IssueInvoice.php with no custom autoloader. Put module tests under autoload-dev so they stay out of production builds.

Each module ships a service provider that wires itself into the framework. Its register method calls mergeConfigFrom so module defaults can be overridden from the app's config. Its boot method calls loadRoutesFrom, loadMigrationsFrom and loadViewsFrom with a namespace such as billing, and registers the module's event listeners through the Event facade. The core application only adds each module provider to its provider list. That keeps the core unaware of module internals and makes each module's footprint visible in one file.

The cost is tooling friction. make: generators write to app/ by default. IDE helper tools and some third-party packages scan only the default paths. Expect to configure paths, write thin wrapper commands, or move generated files by hand.

<?php
// modules/Billing/Providers/BillingServiceProvider.php

namespace Modules\Billing\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Modules\Billing\Events\InvoiceIssued;
use Modules\Billing\Listeners\SendInvoiceEmail;

class BillingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Module defaults live here; the app can override them in config/billing.php
        $this->mergeConfigFrom(__DIR__.'/../config/billing.php', 'billing');
    }

    public function boot(): void
    {
        $root = __DIR__.'/..';

        // The module owns its routes and schema; the core app never lists them
        $this->loadRoutesFrom($root.'/routes/web.php');
        $this->loadMigrationsFrom($root.'/database/migrations');

        // Views are referenced as view('billing::invoices.show')
        $this->loadViewsFrom($root.'/resources/views', 'billing');

        // Event wiring stays inside the domain that handles it
        Event::listen(InvoiceIssued::class, SendInvoiceEmail::class);
    }
}

// composer.json autoload section, then run: composer dump-autoload
//   "autoload":     { "psr-4": { "App\\": "app/", "Modules\\": "modules/" } }
// Module tests stay under autoload-dev so they are excluded with --no-dev.

A self-registering Billing module provider (PHP) that loads its own config, routes, migrations, views and listeners, with the PSR-4 mapping that lets Composer resolve the Modules\ namespace.

How should modules talk to each other without recreating coupling?

A module's public API is the small set of things other modules may depend on: interfaces (contracts), plain DTOs, and action or service classes bound in the container through the module's provider. Everything else is private by convention. That includes Eloquent models, repositories, jobs and internal helpers. Callers type-hint the contract and receive DTOs back.

Do not pass Eloquent models across that boundary. A model exposes its column names, casts and relationships. Any caller that touches $order->customer->address is now coupled to two schemas and can trigger lazy-loaded queries the owning module never planned for. Renaming a column then breaks code you thought was isolated, which is the coupling the module was meant to remove.

Synchronous calls vs. domain events

Concern Interface call Domain event + queued listener
Consistency Immediate, can share a transaction Eventual
Failure Caller sees the exception Retries and failed jobs, often discovered later
Ordering Explicit in code Not guaranteed across workers
Debugging Single stack trace Spread across jobs and logs

Use events when the producer doesn't need the result and a delay is acceptable, such as sending receipts or updating search indexes. Event chains get harder to follow as they grow. Keep them traceable by putting a correlation ID in every event payload, propagating it into job logs, and keeping chains shallow.

Data ownership

Each module owns its tables. Queries must not join across modules or rely on cross-module foreign keys. Store the other module's ID as a plain value. For combined reporting, build a read model fed by events, or a dedicated query service that is allowed to read multiple schemas.

A shared database still couples schema migrations and deployment. Ownership rules keep that coupling visible. They do not eliminate it.

<?php
// Modules/Billing/Contracts/InvoiceLookup.php: public API, safe to depend on
interface InvoiceLookup
{
    public function forOrder(int $orderId): ?InvoiceSummary;
}

// Modules/Billing/Data/InvoiceSummary.php: plain DTO, no Eloquent behavior
final class InvoiceSummary
{
    public function __construct(
        public readonly int $id,
        public readonly int $orderId,   // Orders' ID kept as a plain value, no FK
        public readonly int $totalCents,
        public readonly string $status,
    ) {}
}

// Modules/Billing/Services/EloquentInvoiceLookup.php: private to Billing
final class EloquentInvoiceLookup implements InvoiceLookup
{
    public function forOrder(int $orderId): ?InvoiceSummary
    {
        $invoice = Invoice::query()->where('order_id', $orderId)->first();

        // Map to a DTO so callers never see columns, casts or lazy relations
        return $invoice === null ? null : new InvoiceSummary(
            $invoice->id, $invoice->order_id, $invoice->total_cents, $invoice->status,
        );
    }
}

// Modules/Billing/BillingServiceProvider.php: bind the contract in register()
$this->app->bind(InvoiceLookup::class, EloquentInvoiceLookup::class);

// Modules/Orders/...: the caller type-hints the contract, never the Invoice model
public function __construct(private InvoiceLookup $invoices) {}

This PHP sketch shows a Billing module that exposes a contract and a readonly DTO, binds a private Eloquent-backed implementation in its service provider, and lets the Orders module depend only on the interface.

How do you enforce module boundaries in CI?

A module boundary that exists only in a README is ignored as soon as a deadline makes it easier to reach into another module's internals. One use Modules\Billing\Models\Invoice inside the Orders module often gets through review, and once several exist, your modules are ordinary folders that happen to share a naming convention. The boundary holds only if a build fails when it is crossed.

Architecture tests in the suite

If you use Pest, its architecture expectations let you state rules as tests. For example, you can assert that everything under Modules\Orders does not use Modules\Billing except for the Billing contracts namespace. These rules run with every test run, so developers see a failure locally, before review. Write one rule per module rather than one global rule, so the failure message names the module that broke the boundary.

Static analysis in CI

Deptrac does the same job from a config file. You define each module's public and internal namespaces as layers, then declare which layers may depend on which. Run it as a required CI step. A PHPStan custom rule is another option if you already maintain PHPStan rules.

Per-module testing

Unit and feature tests live inside each module and run alone. Any dependency on another module goes through its contract, so tests bind a fake implementation of that contract in the container. This keeps each module's tests fast and stops them from failing because of an unrelated module's bug. On top of that, keep a thin layer of cross-module integration tests that wires up the real implementations, covering only the flows where modules hand off to each other.

# deptrac.yaml: run in CI as a required step: vendor/bin/deptrac analyse
# Each module has a public layer (Contracts) and an internal layer (everything else).
deptrac:
  paths:
    - ./Modules
  layers:
    - name: OrdersContracts
      collectors:
        - type: classLike
          value: '^Modules\\Orders\\Contracts\\.*'
    - name: OrdersInternal
      collectors:
        - type: bool
          must:
            - type: classLike
              value: '^Modules\\Orders\\.*'
          must_not:
            - type: classLike
              value: '^Modules\\Orders\\Contracts\\.*'
    - name: BillingContracts
      collectors:
        - type: classLike
          value: '^Modules\\Billing\\Contracts\\.*'
    - name: BillingInternal
      collectors:
        - type: bool
          must:
            - type: classLike
              value: '^Modules\\Billing\\.*'
          must_not:
            - type: classLike
              value: '^Modules\\Billing\\Contracts\\.*'
  ruleset:
    # Internals may use their own contracts and other modules' contracts, never other internals.
    OrdersInternal: [OrdersContracts, BillingContracts]
    BillingInternal: [BillingContracts, OrdersContracts]
    # Contracts stay self-contained so they never leak internal types.
    OrdersContracts: []
    BillingContracts: []

A Deptrac config that splits each module into a public Contracts layer and an internal layer, so CI fails when Orders code imports Billing internals such as Modules\Billing\Models\Invoice.

Should you use a Laravel modules package or build your own structure? What are the alternatives?

The structure you choose matters less than whether boundaries are enforced. A modules package solves the first problem but not the second.

A third-party modules package gives you scaffolding commands that generate controllers, migrations, and providers inside a module folder. It also gives you a fixed directory convention and automatic discovery, so modules register their providers, routes, and config without manual wiring. It does not stop one module from importing another's Eloquent models, and it does not design your public interfaces. The architecture tests and contracts from earlier sections are still your job.

The cost is a dependency on how quickly the package is maintained. During a framework upgrade, you may have to wait for the package to support the new release before you can upgrade the app. If the package overrides the framework's file generators or discovery, those overrides are often what break first.

Approach What you get What it costs Fits when
Hand-rolled modules Full control over the layout and providers. Nothing external that can block an upgrade. You write discovery and scaffolding yourself, plus conventions documentation The team is comfortable owning the infrastructure code
Modules package Generators, conventions, and discovery out of the box You depend on its release pace. Upgrades get harder. No enforcement. You want consistency quickly and accept the dependency
Namespaced subfolders in app/ No new tooling. Matches the default framework layout. Boundaries are by convention only, and shared providers keep growing Mid-sized apps that are still finding their boundaries
Separate services Hard runtime isolation and independent deploys Network failures, distributed data, and more operational work The domains need independent scaling or separate team ownership

When should you avoid modularizing, and how do you migrate incrementally?

Modularizing has a real cost. Every boundary adds an interface, a DTO or two, an event class and a provider binding. A five-person team working on a CRUD admin panel or an app with one business capability pays that cost on every change and gets little back, because there is no second domain to protect it from. Also be clear about what modules buy you: code isolation inside one process. They don't give you independent scaling, separate deploys or fault isolation. If those are the goals, the separate-services row in the previous table is the relevant one.

Migrating incrementally

For a large Laravel app that has outgrown app/, migrate one domain at a time:

  1. Pick one well-understood domain. Choose something with clear ownership and few inbound dependencies, such as invoicing, rather than the most tangled area.
  2. Move its code behind an interface. Callers in app/ depend on the contract instead of the concrete classes.
  3. Add a boundary test so that new code cannot bypass the contract.
  4. Leave everything else in app/. It still works, and it doesn't block the move.
  5. Repeat once the first module has been stable through a few release cycles.

You never need a big-bang rewrite.

Illustrative estimate

Assume these inputs. A typical pull request currently touches 12 files across unrelated folders, and a reviewer spends about 4 minutes per file building context. If a module boundary reduces the files a reviewer must understand to 7, review drops from roughly 48 to 28 minutes per PR. At 30 PRs a week, that is about 10 reviewer-hours saved. This is an illustrative estimate, not a measured result. New hires see a similar effect: they can learn one module first instead of the whole codebase.

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 structure, 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.