Skip to content
|By Muhammad Wilayat Shah|26 views • 21 unique IPs

Controller vs Service vs Repository: Where Should Your Logic Go?

A copied API controller oversold pharmacy stock and billed 10-box orders at full price. What belongs in a controller, a service and a repository, shown with a real Laravel refactor, tests and query counts.

ShareLinkedInX
Three layers and one test: the controller speaks HTTP by validating, calling one use case and responding; the service or action owns the business rule, checks, transaction and side effects; the repository hides complex or reused queries without making decisions; and web, API and CLI entry points must give the same answer
Three layers and one test: the controller speaks HTTP by validating, calling one use case and responding; the service or action owns the business rule, checks, transaction and side effects; the repository hides complex or reused queries without making decisions; and web, API and CLI entry points must give the same answer

Last reviewed: 24 Nov 2026

In the pharmacy module of one of our hospital management systems, orders could come from two places: the counter screen used by pharmacy staff and the mobile app used by ward nurses. The web controller had the full order logic: validation, a stock check inside a transaction, a 10% bulk discount from 10 boxes, then the insert. When the mobile app was added, a developer copied that controller into an API controller "for now". A few months later the pharmacy found stock counts going negative, and finance found that 10-box orders from the app were billed at full price. The copy had lost the stock check and turned >= 10 into > 10.

Nobody wrote a bad line on purpose. The rule simply lived in two places, so it drifted. That is the real answer to "controller vs service vs repository": the layers are not there to look tidy, they are there so each business rule has exactly one home. I rebuilt that pharmacy case in a small Laravel 13.43 app on the box (PHP 8.4, SQLite, PHPUnit through php artisan test), and every output below is from that lab.

The short answer

  • Controller: speaks HTTP. Validate input, call one use case, turn the result into a response.
  • Service (or action): holds the business rule and the steps around it: checks, transaction, side effects. It works the same from a web request, an API call, a queue job or an Artisan command.
  • Repository (or query class): hides a query that is complicated, reused or easy to get wrong. It returns data and makes no decisions.
Animated diagram: before, a web controller and an API controller each carry their own copy of the stock check and bulk discount, and the API copy oversells stock and bills the wrong total; after, the web controller, the API controller and an Artisan command all call one PlaceOrder action, which talks to the database, so every entry point gets the same rule
Two copies of a rule drift. One action shared by every entry point cannot.

Quick check: is your logic in the wrong layer?

Open the controller for your busiest feature and look for these signs:

  • A DB::transaction() or lockForUpdate() inside the controller.
  • if statements about money, stock, approval limits or status changes.
  • The same rule in a web controller, an API controller and an Artisan command or job.
  • You cannot test the rule without sending an HTTP request.

The fastest way to prove drift is a test that sends the same order through every entry point. Against the "before" code, with 5 boxes in stock and an order for 8:

Code
$ php artisan test --filter PlaceOrderTest

   FAIL  Tests\Feature\PlaceOrderTest
  ✓ web rejects order larger than stock                  0.13s
  ⨯ api rejects order larger than stock                  0.01s
  ⨯ web and api charge the same for 10 items             0.01s

   FAILED  Tests\Feature\PlaceOrderTest > api rejects order larger than stock
  Expected response status code [422] but received 201.
Failed asserting that 201 is identical to 422.

   FAILED  Tests\Feature\PlaceOrderTest > web and api charge the same for 10 items
  Failed asserting that 10000 is identical to 9000.

  Tests:    2 failed, 1 passed (4 assertions)

The API accepted an order for 8 boxes when only 5 existed, and charged 10,000 for 10 boxes where the counter charged 9,000. Both bugs come from the same cause: the rule had two homes.

What belongs in the controller

After the refactor, the web and API controllers are identical apart from their namespace. They validate, call the action and build the response:

Code
class OrderController extends Controller
{
    public function store(Request $request, PlaceOrder $placeOrder)
    {
        $data = $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);
        $order = $placeOrder->handle($data['product_id'], $data['quantity']);
        return response()->json(['id' => $order->id, 'total' => $order->total], 201);
    }
}

Authentication, authorization, validation (a Form Request when it grows), status codes and response shape belong here. Nothing in this class knows what a bulk discount is. Permission checks also sit at this edge, in middleware or a policy; my Laravel role-based permissions guide shows that part.

What belongs in the service

The rule moved into one small action class. It takes plain values, not a Request, and throws a domain exception instead of building a JSON response:

Code
class PlaceOrder
{
    public const BULK_QUANTITY = 10;

    public function handle(int $productId, int $quantity): Order
    {
        return DB::transaction(function () use ($productId, $quantity) {
            $product = Product::lockForUpdate()->findOrFail($productId);
            if ($product->stock < $quantity) {
                throw new InsufficientStock($product);
            }
            $total = $product->price * $quantity;
            if ($quantity >= self::BULK_QUANTITY) {
                $total = (int) round($total * 0.9);
            }
            $product->decrement('stock', $quantity);
            return Order::create(['product_id' => $product->id, 'quantity' => $quantity, 'total' => $total]);
        });
    }
}

InsufficientStock has a render() method that returns a 422 JSON response, so the HTTP detail stays out of the action while both controllers still answer the same way. With the same tests plus three that call the action directly:

Code
$ php artisan test

   PASS  Tests\Feature\PlaceOrderActionTest
  ✓ bulk discount applies from ten items                 0.11s
  ✓ it refuses to oversell
  ✓ artisan command uses the same rules                  0.01s

   PASS  Tests\Feature\PlaceOrderTest
  ✓ web rejects order larger than stock                  0.03s
  ✓ api rejects order larger than stock                  0.01s
  ✓ web and api charge the same for 10 items             0.01s

  Tests:    6 passed (10 assertions)
  Duration: 0.23s

The line count did not shrink much (56 lines in two controllers before, 63 lines in two controllers plus the action after). That is fine. The point is that the stock and discount rules now exist once.

The real payoff came when pharmacy staff asked for phone orders entered from the terminal. The new Artisan command is a few lines that call the same action, and it refused to oversell without any extra code:

Code
$ php artisan orders:place 1 3
Order #1 placed, total 3000
$ php artisan orders:place 1 3
Only 2 Paracetamol 500mg boxes left in stock.
$ echo $?
1

Keep services small and named after the use case: PlaceOrder, CancelOrder, ApproveInvoice. One OrderService with 40 methods is a fat controller in a different folder.

Animated terminal from the Laravel 13 lab: the before code fails two tests because the API oversells stock and bills 10000 instead of 9000, the refactored code passes all six tests, the orders:place Artisan command refuses to oversell, and a query class cuts a report from 51 queries to 2
The lab, start to finish: failing tests, passing tests, the command, and the query count.

When a repository earns its place

Eloquent is already an abstraction over the database, so wrapping every find() and create() in a repository adds files without adding safety. I add a repository or a small query class when a query is complicated, reused, or easy to get wrong. The pharmacy's recent-orders report is a good example. Written inline in a controller, it lazy-loads each product:

Code
foreach (Order::latest('id')->limit(50)->get() as $order) {
    echo $order->product->name;   // one extra query per order
}

A query class makes the eager load part of the method, so nobody can forget it:

Code
class RecentOrders
{
    public function get(int $limit = 50): Collection
    {
        return Order::query()->with('product')->latest('id')->limit($limit)->get();
    }
}

Counting queries with DB::enableQueryLog() over 50 orders in the lab:

Code
controller loop, lazy loading: 51 queries
RecentOrders query class:      2 queries

That 1 + N pattern is the most common slowdown I see in Laravel reports; my N+1 query guide goes deeper. Notice what the query class does not do: it does not decide which orders are "suspicious" or which customers get blocked. Those are rules, and rules go in a service.

A decision checklist

  1. Is it about HTTP (request, headers, status codes, redirects, sessions)? Controller, middleware or Form Request.
  2. Is it a business rule or a multi-step process? Service or action class.
  3. Will a job, a command or a second API need it? Then it cannot live in a controller.
  4. Is it a complicated or reused query? Model scope, repository or query class.
  5. Is it about how data looks in the response? API Resource or view.

Common mistakes

  • Copying a controller to build the API version instead of extracting the logic first.
  • Services that accept a Request or return a JsonResponse; they can no longer be called from a job or command.
  • Pass-through services and repositories that only forward find($id).
  • Repositories that return a query builder, so every caller adds its own conditions.
  • Important rules hidden in model observers where nobody looks for them.
  • Adding all three layers to every CRUD screen. Start with a thin controller and add an action when a real rule appears.

Questions I get asked

Service class or action class?

Same idea, different size. An action does one use case with one public method. I prefer actions because they are easy to name and find, but a small service grouping two or three closely related methods is fine.

Do I need interfaces for every repository?

No. Add an interface when you really have two implementations (for example a database and an external API) or need to swap one in tests. Otherwise a concrete class is easier to read. The SOLID principles post covers when abstraction pays off.

Does this apply outside Laravel?

Yes. In Node with Express or NestJS, .NET or Django, the same split holds: route handlers speak HTTP, use-case classes hold rules, data-access classes hold queries.


About the author. Muhammad Wilayat Shah is a senior full-stack engineer and team lead based in Islamabad, with 13+ years shipping ERP, HMS, school, fleet and property-portal products on Laravel, PHP, Node.js, React and PostgreSQL. In his team's code reviews, a business rule found in a controller is sent back with one question: what happens when the mobile app needs it? More at wilayats.com/about.

Last reviewed: 24 Nov 2026

ShareLinkedInX
Back to blog

Keep reading

Fix Nginx 413 Request Entity Too Large Error

11/25/2026

Fix Nginx 413 Request Entity Too Large Error

Nginx 413 Request Entity Too Large means a body size limit was hit. Find which layer sent it, then fix client_max_body_size, PHP upload limits, Express and Kubernetes ingress.

Newsletter

Occasional notes on Laravel, React, and shipping production systems — no spam.

Comments

Join the discussion. Replies load on demand, up to 5 levels.

0 threads

Loading editor…
Reviewed before publishing

No comments yet

Be the first to start the conversation.