Why Your Laravel Codebase Is Unmaintainable
Introduction
The Laravel codebases I get called into did not get hard to change in one decision. They drifted. Controllers grew tentacles. Models started knowing about billing and email and PDF generation. At some point someone asks why OrderController depends on ProductController, and nobody in the room can answer.
The drift comes from seven small habits, repeated across every feature, each one productive in the moment and expensive once a second caller needs the same code. This is the architecture deep dive from Top 20 Mistakes Laravel Developers Make. The course Laravel Best Practices: Writing Laravel That Lasts walks the same seven through one codebase, lesson by lesson; this article states each one on its own with a short example.
1. One controller calling another
You need to recalculate an order total from the cart endpoint. OrderController already does it, so you inject it.
<?php
declare(strict_types=1);
namespace App\Cart;
use App\Orders\OrderController;
use Illuminate\Http\JsonResponse;
final class CartController
{
public function __construct(
private OrderController $orders,
) {}
public function update(UpdateCartRequest $request): JsonResponse
{
$items = $request->array('items');
$totalCents = $this->orders->calculateTotal($items);
return new JsonResponse(['total_cents' => $totalCents], 200);
}
}CartController now depends on another controller, a class built to answer HTTP requests. A queued job cannot call that logic. An Artisan command cannot call it. A test for the cart needs the order controller and everything it pulls in. The moment someone adds $request->user() inside calculateTotal, the cart endpoint fails in a way nobody can trace back to the cart.
Extract the calculation into a class with no HTTP in it.
<?php
declare(strict_types=1);
namespace App\Orders;
final readonly class CalculateOrderTotal
{
/**
* @param list<array{quantity: int, unit_price_cents: int}> $items
*/
public function __invoke(array $items): int
{
$total = 0;
foreach ($items as $item) {
$total += $item['quantity'] * $item['unit_price_cents'];
}
return $total;
}
}Both controllers inject CalculateOrderTotal, and so can a job or a test. The lesson Laravel Controllers Calling Other Controllers does this extraction on a reservation flow.
2. Auth::user() in service classes
This one hides until the first job or scheduled command tries to run it.
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Support\Facades\Auth;
final class SubscriptionService
{
public function cancel(int $subscriptionId): void
{
$subscription = Subscription::query()->findOrFail($subscriptionId);
$subscription->cancelled_by = Auth::user()->id;
$subscription->save();
}
}It works from a controller, where a request is active and a user is logged in, and breaks the first time a queue worker or a nightly trial-expiry command runs it, or a test that did not call actingAs() first. The service is lying about its dependencies: the signature says it needs a subscription id, and it needs a subscription id plus a logged-in user on the current request.
Pass the actor in. Take an id rather than the User model: a subscription does not need the whole row to record who cancelled it, and an int keeps App\Subscriptions from depending on App\Models.
<?php
declare(strict_types=1);
namespace App\Subscriptions;
final class SubscriptionService
{
public function cancel(int $subscriptionId, int $cancelledByUserId): void
{
$subscription = Subscription::query()->findOrFail($subscriptionId);
$subscription->cancelled_by = $cancelledByUserId;
$subscription->save();
}
}The controller reads Auth::id() once at the HTTP boundary and hands it over. The job reads it from its payload. The scheduled command passes a system user id. Every caller is explicit. See Laravel Auth::user() Inside the Use Case.
3. Business logic in traits
The trait starts as a way to share two methods, then grows into a billing engine attached to a model.
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Carbon\CarbonImmutable;
trait HasBillingLogic
{
public function calculateProrationCents(CarbonImmutable $upgradeDate): int
{
$daysRemaining = $upgradeDate->diffInDays($this->current_period_end);
$totalDays = $this->current_period_start->diffInDays($this->current_period_end);
return (int) round($this->plan->price_cents * $daysRemaining / $totalDays);
}
public function refundUnusedCents(CarbonImmutable $cancelledAt): int
{
return $this->calculateProrationCents($cancelledAt);
}
}<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class Subscription extends Model
{
use HasBillingLogic;
protected function casts(): array
{
return [
'current_period_start' => 'immutable_datetime',
'current_period_end' => 'immutable_datetime',
];
}
public function plan(): BelongsTo
{
return $this->belongsTo(Plan::class);
}
}Traits share code, not concepts. You cannot replace HasBillingLogic in a test with a double, a stand-in the test controls. You cannot swap in a different billing rule for enterprise customers. You cannot see what the trait depends on without opening it, and every method inside has access to $this, which means access to every property and relation on the model.
Use a class, and let the model call it.
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Carbon\CarbonImmutable;
final readonly class ProrationCalculator
{
public function forPeriod(
CarbonImmutable $periodStart,
CarbonImmutable $periodEnd,
int $periodPriceCents,
CarbonImmutable $at,
): int {
$daysRemaining = $at->diffInDays($periodEnd);
$totalDays = $periodStart->diffInDays($periodEnd);
return (int) round($periodPriceCents * $daysRemaining / $totalDays);
}
}<?php
declare(strict_types=1);
namespace App\Subscriptions;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class Subscription extends Model
{
protected function casts(): array
{
return [
'current_period_start' => 'immutable_datetime',
'current_period_end' => 'immutable_datetime',
];
}
public function plan(): BelongsTo
{
return $this->belongsTo(Plan::class);
}
public function prorationCents(ProrationCalculator $calculator, CarbonImmutable $upgradeDate): int
{
return $calculator->forPeriod(
$this->current_period_start,
$this->current_period_end,
$this->plan->price_cents,
$upgradeDate,
);
}
}ProrationCalculator is a class whose one method you can call in a unit test with four arguments and no database, and read end to end. Traits stay for mechanics like HasFactory and SoftDeletes. The lesson Laravel Traits for Business Rules moves a pricing rule out of a trait the same way.
4. Files that never get split
The 640-line controller is what refusing to split by use case looks like after enough features.
InvoiceController
index() 40 lines
show() 30 lines
store() 120 lines
update() 90 lines
markPaid() 60 lines
void() 80 lines
regeneratePdf() 150 lines
sendReminder() 70 linesEight actions, eight different reasons to change the file, and any two pull requests that touch invoices can conflict. The methods share a class but not a purpose. Testing one means loading the dependencies of all eight.
Split by use case: one action per controller, one command per action. A command is a small object that names the action and carries its input.
<?php
declare(strict_types=1);
namespace App\Billing;
use Carbon\CarbonImmutable;
final readonly class MarkInvoicePaidCommand
{
public function __construct(
public int $invoiceId,
public CarbonImmutable $paidAt,
public string $reference,
) {}
}The controller hands the command to Laravel's command bus, Illuminate\Contracts\Bus\Dispatcher, which finds that command's handler, the class that does the work, and runs it. Dispatching through the bus returns whatever the handler returns, once the command is mapped to its handler with Bus::map() in a service provider. Here BillingServiceProvider needs Bus::map([MarkInvoicePaidCommand::class => MarkInvoicePaidCommandHandler::class]);.
<?php
declare(strict_types=1);
namespace App\Billing;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
final readonly class MarkInvoicePaidController
{
public function __construct(
private Dispatcher $bus,
) {}
public function __invoke(MarkInvoicePaidRequest $request, int $invoiceId): JsonResponse
{
$this->bus->dispatch(new MarkInvoicePaidCommand(
invoiceId: $invoiceId,
paidAt: $request->date('paid_at')->toImmutable(),
reference: $request->string('reference')->toString(),
));
return new JsonResponse(status: 204);
}
}Each file has one reason to change. Each test loads one thing. The diff in a pull request names the action that moved. See Laravel Resource Controllers That Never Get Split.
5. The default folder structure
app/Http/Controllers, app/Models, app/Services, app/Jobs. The layout is fine while the app has a handful of features. Once it has dozens, nothing related to billing lives near anything else related to billing.
app/
Http/Controllers/InvoiceController.php
Http/Controllers/SubscriptionController.php
Http/Controllers/ProductController.php
Models/Invoice.php
Models/Subscription.php
Models/Product.php
Services/InvoiceService.php
Services/SubscriptionService.php
Jobs/SendInvoiceReminder.php
Jobs/ChargeSubscription.php
Listeners/RecordInvoiceHistory.php
Listeners/RecordSubscriptionHistory.phpTo change how invoices work you open five folders. The structure tells you what each file is and nothing about what the app does.
Group by module instead: one folder per business capability, holding everything that capability needs.
app/
Billing/
Invoice.php
MarkInvoicePaidCommand.php
MarkInvoicePaidCommandHandler.php
MarkInvoicePaidController.php
SendInvoiceReminder.php
BillingServiceProvider.php
Catalog/
Product.php
CreateProductCommand.php
CreateProductCommandHandler.php
CreateProductController.php
Subscriptions/
Subscription.php
CancelSubscriptionCommand.php
CancelSubscriptionCommandHandler.phpOpen the folder and the feature is there. A new engineer reads the system module by module instead of folder by folder.
Adding Billing/Http/, Billing/Models/ and Billing/Jobs/ rebuilds the default layout inside each module. Each file's name already says what it does, and the whole feature fits in one place you can read top to bottom.
6. app() instead of constructor injection
Anywhere you see this, there is a class lying about what it needs.
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use App\Billing\PaymentGateway;
use App\Billing\PaymentReceipt;
use Illuminate\Contracts\Mail\Mailer;
use Psr\Log\LoggerInterface;
final class ChargeSubscription
{
public function handle(int $subscriptionId): void
{
$gateway = app(PaymentGateway::class);
$mailer = app(Mailer::class);
$logger = app(LoggerInterface::class);
$subscription = Subscription::query()->findOrFail($subscriptionId);
$charge = $gateway->charge($subscription->payment_method_id, $subscription->plan->price_cents);
$mailer->to($subscription->billing_email)->send(new PaymentReceipt($charge->id));
$logger->info('Subscription charged', ['subscription_id' => $subscription->id]);
}
}The signature says handle(int $subscriptionId). The class also needs a payment gateway, a mailer, and a logger, and the app() calls hide all three. A test cannot replace them without booting the container and binding fakes. A reader cannot tell what this class touches without scanning every line.
Inject the dependencies.
<?php
declare(strict_types=1);
namespace App\Subscriptions;
use App\Billing\PaymentGateway;
use App\Billing\PaymentReceipt;
use Illuminate\Contracts\Mail\Mailer;
use Psr\Log\LoggerInterface;
final readonly class ChargeSubscription
{
public function __construct(
private PaymentGateway $gateway,
private Mailer $mailer,
private LoggerInterface $logger,
) {}
public function handle(int $subscriptionId): void
{
$subscription = Subscription::query()->findOrFail($subscriptionId);
$charge = $this->gateway->charge($subscription->payment_method_id, $subscription->plan->price_cents);
$this->mailer->to($subscription->billing_email)->send(new PaymentReceipt($charge->id));
$this->logger->info('Subscription charged', ['subscription_id' => $subscription->id]);
}
}The constructor is the truth about what this class needs. A test passes in doubles directly. The container wires it once at boot and stays out of the way. See Laravel Dependency Injection vs Facades and app().
7. Treating MVC as the architecture
MVC separates a user interface from its data. It is not an application architecture. When the whole mental model is "fat controller or fat model", there are two places to put everything and no way to name anything.
The fat-controller version:
<?php
declare(strict_types=1);
namespace App\Orders;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Mail;
final class OrderController
{
public function store(StoreOrderRequest $request): JsonResponse
{
$order = Order::create($request->validated());
foreach ($request->array('items') as $item) {
$order->items()->create($item);
}
$order->total_cents = $order->items->sum('price_cents');
$order->save();
Mail::to($order->customer)->send(new OrderConfirmation($order));
event(new OrderPlaced($order));
return new JsonResponse($order, 201);
}
}The fat-model version hides the same code behind Order::placeFrom($request): the same coupling, moved one file over. The Mail facade and the event() helper in that method are mistake 6 showing up again, and they compound with the missing structure.
Give the operation a name, a handler, and an event. The command names the intent:
<?php
declare(strict_types=1);
namespace App\Orders;
final readonly class PlaceOrderCommand
{
/**
* @param list<array{product_id: int, quantity: int, price_cents: int}> $items
*/
public function __construct(
public int $customerId,
public array $items,
) {}
}The model owns the rules for building a valid order:
<?php
declare(strict_types=1);
namespace App\Orders;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Order extends Model
{
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
public function items(): HasMany
{
return $this->hasMany(OrderItem::class);
}
/**
* @param list<array{product_id: int, quantity: int, price_cents: int}> $items
*/
public static function placeFor(int $customerId, array $items): self
{
$totalCents = 0;
foreach ($items as $item) {
$totalCents += $item['quantity'] * $item['price_cents'];
}
$order = self::query()->create([
'customer_id' => $customerId,
'total_cents' => $totalCents,
]);
$order->items()->createMany($items);
return $order;
}
}The app calls Model::unguard() in AppServiceProvider, the way Writing Laravel That Lasts does when it moves the reservations into a module, so the models declare no $fillable.
The handler coordinates: build, then announce. It wraps the order and item inserts in one transaction and dispatches the event with the order id, not the model:
<?php
declare(strict_types=1);
namespace App\Orders;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\ConnectionInterface;
final readonly class PlaceOrderCommandHandler
{
public function __construct(
private ConnectionInterface $connection,
private Dispatcher $events,
) {}
public function handle(PlaceOrderCommand $command): Order
{
$order = $this->connection->transaction(fn (): Order => Order::placeFor($command->customerId, $command->items));
$this->events->dispatch(new OrderPlaced($order->id));
return $order;
}
}The event carries only that id:
<?php
declare(strict_types=1);
namespace App\Orders;
final readonly class OrderPlaced
{
public function __construct(
public int $orderId,
) {}
}The email is a side effect of the event, so a listener sends it through an injected mailer:
<?php
declare(strict_types=1);
namespace App\Orders;
use Illuminate\Contracts\Mail\Mailer;
final readonly class SendOrderConfirmation
{
public function __construct(
private Mailer $mailer,
) {}
public function handle(OrderPlaced $event): void
{
$order = Order::query()->with('customer')->findOrFail($event->orderId);
$this->mailer->to($order->customer->email)->send(new OrderConfirmation($order->id));
}
}The controller translates the request into the command and renders the result:
<?php
declare(strict_types=1);
namespace App\Orders;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
final readonly class PlaceOrderController
{
public function __construct(
private Dispatcher $bus,
) {}
public function __invoke(PlaceOrderRequest $request): JsonResponse
{
$order = $this->bus->dispatch(new PlaceOrderCommand(
customerId: $request->user()->id,
items: $request->array('items'),
));
return new JsonResponse(['data' => ['id' => $order->id]], 201);
}
}The module's service provider, registered in bootstrap/providers.php, maps the command to its handler and the event to its listener; facades are fine in a provider:
<?php
declare(strict_types=1);
namespace App\Orders;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
final class OrdersServiceProvider extends ServiceProvider
{
public function boot(): void
{
Bus::map([PlaceOrderCommand::class => PlaceOrderCommandHandler::class]);
Event::listen(OrderPlaced::class, SendOrderConfirmation::class);
}
}Each piece has one job: the controller speaks HTTP, the handler coordinates, the model owns its state, the event announces what happened, the listener reacts. MVC is fine for a CRUD admin panel. For anything with business rules, reach for commands, handlers, and events. Sections 5 and 7 are one argument, and Laravel Folder Structure Is Not an Architecture makes it in full; Laravel Command Bus for a Use Case Without a Shape adds the command, handler and event.
Where to start in an existing codebase
Do not start with the folder move. Start with mistake 6: replace app() calls with constructor injection, file by file. It is mechanical and rarely changes behaviour, and it makes the next steps testable. Then extract the shared logic out of controllers (mistake 1), and pass the actor in (mistake 2), which gives you the first use case classes. Split the fattest controller (mistake 4) once those classes exist. Move to modules last, when there are enough use case classes that the folder move is a rename. The signal that tells you which mistake you are looking at is always the same: a job, an Artisan command, or a test needs code that only a controller can currently run.
Related Links
- Top 20 Mistakes Laravel Developers Makethe pillar index this deep dive sits under
- Laravel Best Practices: Writing Laravel That Lastsits Architecture and Code Organization chapter refactors one reservation flow through all seven of these
- Why Your Laravel App Is Slowmultiple writes per use case, eager loading on the model, queries in accessors, reporting in Eloquent, SELECT *, and filtering in PHP
- Stop Writing Laravel APIs Like Thismass assignment from validated(), raw request values, one endpoint with many intents, and one Form Request for create and update
- Your Laravel Code Needs More Objectsarrays as data bags, Eloquent models passed through every layer, and primitives where value objects belong