Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 67 ยท Architecture and Extending

Architecture in Laravel: Actions, Services and DTOs

Slim down fat Laravel controllers with action classes, services and DTOs, learn when repositories are not worth it, and use events to decouple side effects.

Every Laravel project starts clean. A controller validates a request, saves a model and redirects. Then come the requirements: send a welcome email, apply a coupon, notify the sales team, write an audit entry, charge a card. A year later the store() method is 200 lines long, nobody dares to touch it, and the only way to test it is to make a fake HTTP request to the whole application. That is the fat controller problem.

Laravel does not force an architecture on you, which is a strength and a trap. In this lesson you will learn a small set of patterns that keep code readable as it grows: action classes, services, data transfer objects (DTOs), events, and an honest view of repositories. The goal is not "more layers". The goal is that each piece of code has one job and a name that says what it is. For the general principles behind this, see OOP design principles. Laravel code here is read-only; the runnable example is a plain-PHP refactoring you can follow step by step.

The fat controller

Here is a typical offender, shortened:

PHP
class OrderController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'product_id' => ['required', 'exists:products,id'],
            'quantity'   => ['required', 'integer', 'min:1'],
            'coupon'     => ['nullable', 'string'],
        ]);

        $product = Product::findOrFail($data['product_id']);

        if ($product->stock < $data['quantity']) {
            return back()->withErrors(['quantity' => 'Not enough stock.']);
        }

        $total = $product->price * $data['quantity'];
        if (! empty($data['coupon']) && $data['coupon'] === 'SAVE10') {
            $total = (int) round($total * 0.9);
        }

        $order = Order::create([
            'user_id'    => $request->user()->id,
            'product_id' => $product->id,
            'quantity'   => $data['quantity'],
            'total'      => $total,
        ]);

        $product->decrement('stock', $data['quantity']);

        Mail::to($request->user())->send(new OrderPlaced($order));
        Log::info('Order placed', ['order' => $order->id]);

        return redirect()->route('orders.show', $order);
    }
}

Nothing here is wrong, but the controller knows about validation, stock rules, pricing, persistence, email and logging. You cannot reuse the "place an order" logic from an Artisan command, a queued job or an API endpoint without copying it. The controller should only translate between HTTP and your application: read the request, call the business logic, return a response.

flowchart LR
    C["Controller<br/>(HTTP in, HTTP out)"] --> A["Action: PlaceOrder"]
    A --> P["PricingService"]
    A --> M["Eloquent models"]
    A --> E["Event: OrderPlaced"]
    E --> L1["Listener: send email"]
    E --> L2["Listener: write audit log"]

The controller stays thin. The action orchestrates one use case, and side effects hang off an event.

Step 1: validation moves to a form request

Validation belongs in a form request, which already gives you authorize(), rules() and validated(). This alone removes the first 8 lines.

Step 2: a DTO carries the validated data

A data transfer object is a small, typed, immutable object that carries data between layers. Instead of passing a loose array whose keys you must remember, you pass something with named, typed properties:

PHP
namespace App\Data;

final readonly class PlaceOrderData
{
    public function __construct(
        public int $userId,
        public int $productId,
        public int $quantity,
        public ?string $coupon = null,
    ) {}

    public static function fromRequest(PlaceOrderRequest $request): self
    {
        return new self(
            userId: $request->user()->id,
            productId: $request->integer('product_id'),
            quantity: $request->integer('quantity'),
            coupon: $request->input('coupon'),
        );
    }
}

Now the action does not depend on Request at all. It can be called from a controller, a console command or a test with a plain new PlaceOrderData(...). A typo in a property name is caught by your editor and by static analysis, which an array key never is.

Step 3: an action class does one thing

An action is a class with one public method (usually handle() or execute()) that performs a single use case: PlaceOrder, CancelSubscription, PublishPost. The name is a verb phrase, so the folder app/Actions reads like a list of what your application can do.

PHP
namespace App\Actions;

final class PlaceOrder
{
    public function __construct(private PricingService $pricing) {}

    public function handle(PlaceOrderData $data): Order
    {
        return DB::transaction(function () use ($data) {
            $product = Product::lockForUpdate()->findOrFail($data->productId);

            if ($product->stock < $data->quantity) {
                throw new InsufficientStockException($product);
            }

            $order = Order::create([
                'user_id'    => $data->userId,
                'product_id' => $product->id,
                'quantity'   => $data->quantity,
                'total'      => $this->pricing->total($product->price, $data->quantity, $data->coupon),
            ]);

            $product->decrement('stock', $data->quantity);

            OrderPlaced::dispatch($order);

            return $order;
        });
    }
}

And the controller becomes a few lines. Laravel's container builds the action for you, including its constructor dependencies (service container):

PHP
public function store(PlaceOrderRequest $request, PlaceOrder $placeOrder)
{
    $order = $placeOrder->handle(PlaceOrderData::fromRequest($request));

    return redirect()->route('orders.show', $order);
}

The business error is a custom exception, which the exception handler can render as a validation-style message (logging and errors). Actions can be called from anywhere, including jobs and commands, so the same rule is enforced everywhere.

Services: reusable domain logic

An action is one use case. A service is a group of related capabilities that several actions share, such as PricingService (totals, discounts, tax) or InvoiceNumberGenerator. Services are usually plain classes with no knowledge of HTTP.

Two warnings about services:

  • Do not create a UserService with 40 methods that is just the old fat controller in a new folder. If you cannot say in one sentence what a service is for, split it.
  • Prefer small classes with clear names. PricingService is good; Helper, Manager and Utils are red flags.

Events: decouple the side effects

Look again at the fat controller: emailing the customer and writing a log line are not part of placing an order; they are reactions to it. Dispatch an event and let listeners handle each reaction (events and listeners). The action does not need to know that an email exists, and you can add a Slack notification later without editing the action. Queued listeners also keep slow work, like email, out of the request.

Use events for reactions that other parts of the system may want to hear about. Do not use them for the main steps of your logic: if "charge the card" is essential to placing an order, call it directly so that the flow is easy to follow and a failure stops the order.

Repositories: usually not needed

Many tutorials add a repository layer: an interface such as OrderRepositoryInterface with an Eloquent implementation. In Laravel this is often unnecessary. Eloquent is already an abstraction over the database, with scopes, relationships and query builders. A repository on top of it tends to copy Eloquent's methods one by one and adds files without removing coupling.

Consider a repository only when you have a real reason:

  • You genuinely swap data sources (for example Eloquent in production and an API client elsewhere).
  • You want to hide a complex, reusable query behind a meaningful name. Often a query scope or a dedicated query class does that with less ceremony.
  • You are working in a large domain-driven codebase where the rule is already established.

"So I can swap the database later" is almost never a good reason: it almost never happens, and Laravel's query builder already supports several engines.

A refactoring you can run

The stand-in below does the same refactoring in plain PHP. Part 1 is the fat version, with everything in one function. Part 2 splits it into a DTO, a pricing service, an action and an event dispatcher, and shows that the action can be tested without any HTTP layer. Both versions print the same result for the same input.

PHP From a fat controller to an action with a DTO

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice what changed: the arithmetic lives in PricingService, so you can test discounts with plain numbers; the action can run from a console command; and the email is a listener, not a line in the middle of the order logic.

Keeping it simple

Patterns are tools, not rules. A few guidelines keep you out of over-engineering:

  • Start in the controller. A five-line store() that calls Eloquent is fine. Extract an action when logic is reused, grows beyond a screenful, or is hard to test.
  • One action, one verb. If the name needs "And" in it (CreateUserAndSendEmail), you have two actions or an action plus an event.
  • Put rules close to the data they protect. A method like $order->markAsPaid() or $post->isPublished() on the model is often better than a service. Eloquent models are allowed to have behavior.
  • Name things after the business. PlaceOrder, ApproveInvoice and PricingService tell a newcomer what your app does. OrderManager does not.
  • Follow the framework. Form requests for validation, policies for authorization, jobs for slow work, events for reactions, resources for JSON. Reaching for Laravel's own building block first keeps the code familiar to every Laravel developer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should a controller mainly be responsible for?

    A thin controller delegates business rules to actions, services and models, so those can be reused from jobs and commands and tested without HTTP.
  2. 2. What is the main benefit of passing a DTO to an action instead of the Request object?

    A typed, immutable DTO can be built from a request, a console input or a test. The action does not care where the data came from, and your editor catches property typos.
  3. 3. Which statement about repositories in a typical Laravel app is most accurate?

    A repository that mirrors Eloquent method by method adds files without reducing coupling. Scopes or query classes usually give named queries with less ceremony.
  4. 4. When is an event the right tool?

    Events decouple optional side effects from the main flow. Essential steps should be called directly so the flow is easy to follow and failures stop the use case.

Summary

  • A fat controller mixes HTTP, validation, business rules, persistence and side effects; keep controllers thin.
  • Form requests handle validation, DTOs carry typed data, and action classes perform one use case each.
  • Services group related reusable logic; avoid giant "manager" or "helper" classes.
  • Dispatch events for reactions such as email and auditing, but call essential steps directly.
  • Do not add repositories by default; Eloquent, scopes and query classes are often enough.
  • Start simple and extract patterns when the code asks for them.

Next: Packages and Extending Laravel