Killing Fat Controllers in Laravel: Actions as the Home for Business Logic: 03 of 08

Why controllers get fat, how to move business rules into single-purpose Action classes, what a good Action looks like, and when the pattern costs more than it gives. One invoice feature, three entry points.

Killing Fat Controllers in Laravel: Actions as the Home for Business Logic: 03 of 08
Photo by Abdullahi Mohamud ✪ / Unsplash

Picture a store method that begins at line 12 and ends at line 190. It validates the request, loads the invoice, checks that its status allows approval, totals the lines, applies tax, writes an audit row, flips the status, sends an email and returns a redirect. Nobody planned it that way. It grew one reasonable request at a time, and each time the cheapest place for the new rule was the method that already had the request in hand.

Then the product asks for a bulk approve command for month end, and a few weeks later for an API endpoint. The team now has three options, all bad: copy the logic, call the controller from the command, or fake an HTTP request inside a console job.

This article follows that one feature, approving an invoice, through the web UI, a console command and an API, to show where the logic should live so that it exists exactly once. It builds on the tenant context from the previous article in the series. Data objects, Concerns and Events come next.

Why Controllers Get Fat

Fat controllers are rarely a skill problem. They are a gravity problem. A controller method is the first place in the code that holds everything at once: the user, the input, the route-bound models. Logic collects where its inputs already are.

The price shows up later. Logic trapped behind an HTTP request can't be reused by a command, a queued job or another endpoint. Testing it means booting the whole HTTP stack. And reading it means scrolling past validation and redirects to find the one rule you came for.

Exhortation won't fix this. Logic needs a better home that has the same inputs, and a controller needs a short list of things it is still allowed to do.

What the Controller Is Still Allowed to Do

Four jobs, and only these:

  • Authorize the request (a policy or a gate).
  • Validate the input (a Form Request).
  • Call one Action.
  • Turn the outcome into an HTTP response.

Here is the approval endpoint after the move:

class InvoiceApprovalController extends Controller
{
    public function store(
        Request $request,
        Company $company,
        Invoice $invoice,
        ApproveInvoice $approve,
    ): RedirectResponse {
        Gate::authorize('approve', $invoice);

        try {
            $approve->handle($invoice, $request->user());
        } catch (InvoiceCannotBeApproved $e) {
            return back()->withErrors(['invoice' => $e->getMessage()]);
        }

        return redirect()->route('invoices.show', [$company, $invoice]);
    }
}

One detail that trips people in a company-prefixed app: Laravel hands route parameters to the method in order, so the {company} from the prefix has to appear in the signature even when the body doesn't need it.

The method reads in ten seconds. It says who may do this, what happens, and what the user sees when it fails. Nothing in it knows what approving an invoice means.

Anatomy of an Action

An Action is a plain class with one public method, named after one use case. No base class is required and Laravel doesn't ship one. The conventions that have worked for me are few:

  • The class name is a verb phrase: ApproveInvoice, not InvoiceService.
  • Dependencies come through the constructor, so the container can build it anywhere.
  • The method receives everything it needs as arguments. It never reads the request, the session or auth()->user().
  • It owns the transaction.
  • It signals business failures with exceptions named after the rule that failed.

The same rule from the tenant article applies: nothing reaches for ambient state. The caller says who is approving.

final class ApproveInvoice
{
    public function handle(Invoice $invoice, ?User $approver): Invoice
    {
        return DB::transaction(function () use ($invoice, $approver): Invoice {
            $invoice = Invoice::query()->lockForUpdate()->findOrFail($invoice->id);

            if ($invoice->status !== InvoiceStatus::PendingApproval) {
                throw InvoiceCannotBeApproved::because($invoice->status);
            }

            $invoice->update([
                'status' => InvoiceStatus::Approved,
                'approved_by' => $approver?->id,
                'approved_at' => now(),
            ]);

            return $invoice;
        });
    }
}

final class InvoiceCannotBeApproved extends RuntimeException
{
    public static function because(InvoiceStatus $status): self
    {
        return new self("An invoice in status {$status->value} cannot be approved.");
    }
}

The lockForUpdate earns its place. If two approvers click at the same second, both requests could read the invoice as pending. Reloading it under a lock inside the transaction, and checking the status after, means the second one fails cleanly. Notice that the reload goes through the tenant scope too, so the Action can't approve another company's invoice even if a caller passes a bad model.

A null approver means the system did it. That is a decision about this domain, and it costs a nullable column. Your domain may prefer a dedicated system user.

Same Action, Three Doors

Now the month-end command. It has to pick a company explicitly, because a console command has no URL and no logged-in user:

class ApproveDueInvoices extends Command
{
    protected $signature = 'invoices:approve-due {company}';

    public function handle(TenantContext $tenant, ApproveInvoice $approve): int
    {
        $company = Company::where('slug', $this->argument('company'))->firstOrFail();

        $tenant->runAs($company->id, function () use ($approve): void {
            Invoice::query()
                ->where('status', InvoiceStatus::PendingApproval)
                ->each(function (Invoice $invoice) use ($approve): void {
                    try {
                        $approve->handle($invoice, null);
                    } catch (InvoiceCannotBeApproved $e) {
                        $this->warn("Skipped {$invoice->number}: {$e->getMessage()}");
                    }
                });
        });

        return self::SUCCESS;
    }
}

The API endpoint is the controller again with a different ending: it returns a resource or a 409 instead of a redirect. Three doors, three ways of presenting a failure, one rule. When finance changes what "approvable" means, there is one file to edit.

Testing Gets Cheaper

The rule now lives where it can be tested without HTTP:

it('approves a pending invoice', function () {
    $company = Company::factory()->create();

    $invoice = app(TenantContext::class)->runAs($company->id, function () {
        $pending = Invoice::factory()->pendingApproval()->create();

        return app(ApproveInvoice::class)->handle($pending, User::factory()->create());
    });

    expect($invoice->status)->toBe(InvoiceStatus::Approved);
});

it('refuses to approve the same invoice twice', function () {
    $company = Company::factory()->create();

    app(TenantContext::class)->runAs($company->id, function () {
        $approved = Invoice::factory()->approved()->create();

        app(ApproveInvoice::class)->handle($approved, null);
    });
})->throws(InvoiceCannotBeApproved::class);

The factory states pendingApproval() and approved() are assumed here. What matters is the split: the rules are tested once, at the Action. The controller test only has to prove the wiring. Guests are redirected, non-approvers get a 403, and a failure comes back as a validation error.

When an Action Is Too Much

This pattern has costs, and they are real. Each Action is a file, a name and a hop for the reader. Applied everywhere, it turns a plain update of a customer's phone number into ceremony.

Three smells tell you it has gone too far, or not far enough:

  • Pass-through Actions. If handle is one Eloquent call, the Action adds a file and removes nothing. Keep simple CRUD in the controller.
  • Actions calling Actions. A little is fine. A chain of five becomes a hidden call graph that is harder to follow than the fat controller was. Compose in one higher-level Action instead, and keep it readable.
  • A handle with eight parameters. The inputs want to be a typed object. That is the next article.

It is also worth saying what an Action is not. An InvoiceService with twelve methods is the fat controller moved one folder over. The discipline is in one use case per class.

My rule of thumb is to extract an Action when a second caller appears, or when a controller method stops fitting on one screen. Before that, the extra indirection costs more than it returns.

Conclusion

The 190-line method didn't need cleverer code. It needed the rule to live somewhere that a controller, a command and an endpoint could all call, and a controller that was allowed to do four small things. Pick the fattest method in your app, find the rule that already has a second caller, and extract only that one.

In the next article we deal with what still feels messy around an Action: the array of loose inputs, the traits that become junk drawers, and the emails and ledger updates that don't belong inside the transaction.