Once the strangler fig from Part 1 is working, the new Laravel app grows fast. Each migrated route brings a feature with it: dealers, orders, invoices, stock. Teams usually organise that into modules, something like app/Modules/Orders, app/Modules/Billing, app/Modules/Inventory. For a few months it feels clean. Then someone adds a call from Billing into Orders to check a status, someone else adds a call from Orders into Billing to fetch a price, and a year later every module imports every other one. You have rebuilt the legacy ball of mud, only with nicer folders.
I see this pattern often enough that I now add a dependency check before the second module exists. This post shows how to find cycles in an existing modular Laravel app, how to break them without a rewrite, and how to stop them from coming back.
I wrote this with help from AI tools and checked the commands against the deptrac and Laravel documentation. I am a Principal Software Engineer in Karachi with 9+ years across PHP/Laravel, Vue, Node and .NET microservices, and this is how we structure modernization projects at Loop Origin.
📚 Series Navigation — Modernizing Legacy PHP Without a Rewrite
Part 1: Strangler Fig for Legacy PHP: Run Old and New Side by Side Part 2 (This Post): Untangling Dependency Cycles in a Modular Laravel Monolith Part 3: Upgrading Old PHP Versions Safely With Rector and CI Part 4: Replacing Legacy Auth & Sessions Without Logging Everyone Out Part 5: From FTP Deploys and Cron Scripts to a Real Pipeline Part 6: Decommissioning the Old App: Shadow Traffic, Flags & Final Cutover Related earlier posts: Characterization Tests Before You Refactor AI-Written Code · Zero-Downtime Database Migrations in Laravel & Node.js SaaS
Direct answer: Map which modules import which with a tool like deptrac, pick a direction for each relationship, and break every reverse edge. Use a published interface (contract) for synchronous reads, domain events for reactions, and an anti-corruption layer for legacy data. Then fail CI on any new violation.
A cycle between two modules means neither can change, be tested or be extracted alone. In practice it shows up as:
The goal is not zero dependencies. It is a dependency graph that points in one direction, so lower modules never know about higher ones.
Start by measuring. deptrac lets you declare layers (here, modules) and reports every class-level dependency between them. A minimal config for a modular Laravel app:
deptrac:
paths: ["./app/Modules"]
layers:
- { name: Orders, collectors: [{ type: directory, value: app/Modules/Orders/.* }] }
- { name: Billing, collectors: [{ type: directory, value: app/Modules/Billing/.* }] }
- { name: Inventory, collectors: [{ type: directory, value: app/Modules/Inventory/.* }] }
- { name: Shared, collectors: [{ type: directory, value: app/Modules/Shared/.* }] }
ruleset:
Orders: [Inventory, Shared, Billing]
Billing: [Shared]
Inventory: [Shared]
Shared: []
Run vendor/bin/deptrac analyse and it lists every violation with file and line. On the first run in an older codebase, expect dozens. Do not try to fix them all at once. Record the current state as a baseline (deptrac analyse --formatter=baseline), so CI only fails on new violations while you work through the old ones.
If you just want a quick picture before installing anything, a crude import count already tells you where the knots are:
for m in Orders Billing Inventory; do
echo "== $m imports:"
grep -rhoE "use App\\\\Modules\\\\[A-Za-z]+" app/Modules/$m \
| sed 's/.*Modules\\//' | sort | uniq -c | grep -v " $m$"
done
For each pair of modules that depend on each other, decide which one is "lower". My rule of thumb: the module that would still make sense if the other disappeared is lower. Billing can exist without knowing about order screens; Orders cannot place an order without a price. So Orders may depend on Billing, and Billing must not depend on Orders.
There are three tools, and choosing the right one for each edge matters:
| Technique | Use when | Example | Trade-off |
|---|---|---|---|
| Contract (interface) | The lower module needs to call the higher one synchronously for data | Billing needs order totals: define OrderTotals in Billing, implement it in Orders |
Still a runtime link, but the direction is inverted |
| Domain event | The lower module only needs to react after something happens | Billing listens to OrderPlaced to create an invoice |
Eventual consistency, needs idempotent listeners |
| Anti-corruption layer | A module keeps reaching into legacy tables or another module's models | Inventory reads old tbl_stock through aLegacyStockReader |
Extra mapping code, but isolates the mess |
The lower module owns the interface; the higher module implements it and binds it in its service provider.
// app/Modules/Billing/Contracts/OrderTotals.php
namespace App\Modules\Billing\Contracts;
interface OrderTotals
{
public function forOrder(int $orderId): Money;
}
// app/Modules/Orders/Billing/EloquentOrderTotals.php
final class EloquentOrderTotals implements \App\Modules\Billing\Contracts\OrderTotals
{
public function forOrder(int $orderId): Money
{
return Money::ofMinor(Order::findOrFail($orderId)->lines()->sum('total_minor'), 'USD');
}
}
// app/Modules/Orders/OrdersServiceProvider.php
$this->app->bind(OrderTotals::class, EloquentOrderTotals::class);
Billing now depends only on its own interface. deptrac sees Orders → Billing, which is the allowed direction.
// Orders dispatches, knowing nothing about who listens
OrderPlaced::dispatch($order->id, $order->tenant_id);
// Billing listens, idempotently
final class CreateInvoiceForOrder implements ShouldQueue
{
public function handle(OrderPlaced $e): void
{
Invoice::firstOrCreate(['order_id' => $e->orderId], [...]);
}
}
Keep event classes in a small shared module, or in the producing module with plain scalar payloads, so listeners never need the producer's Eloquent models.
The most common source of new cycles is an Eloquent model from one module showing up in another module's method signatures. Once Billing accepts an Orders\Models\Order, it can lazy-load anything. Pass ids or small read-only DTOs across module boundaries instead. It feels like extra typing for a week and saves months later.
- name: Module boundaries
run: vendor/bin/deptrac analyse --fail-on-uncovered --report-uncovered --no-progress
With the baseline in place, this blocks any pull request that adds a new reverse dependency, while the team burns down the old ones a few per sprint. On our projects, we treat the baseline count as a number on the migration ledger from Part 1: it should only go down.
If your modular monolith has already tangled and you want a second pair of eyes, our Laravel development page explains how we approach these refactors, and you can contact us with a short description of the modules involved.
No. Plain folders under app/Modules with their own service providers are enough. A package can help with scaffolding, but boundaries come from rules and CI, not from the folder tool.
No. PHPArch and PHPat can express similar rules as tests, and some teams write a small custom PHPStan rule. Pick one and run it in CI; the tool matters less than enforcing it.
A little. Log the event name and correlation id when it is dispatched and handled, so you can follow a request across modules in your logs.
As little as possible: value objects like Money, base exceptions and event classes. If Shared starts holding business logic, it becomes the new tangle.
Not at this stage. Separate table ownership, enforced in code, is enough. Splitting databases only makes sense if you later extract a module into its own service.
On a mid-sized app, the first baseline and CI rule take a day. Burning down the old violations is ongoing work, usually spread across a few months alongside features.
Next in this series, Part 3 covers upgrading old PHP versions safely with Rector and CI.