Keeping Controllers Thin: Services and Folder Organization
Your invoice app has been running for two months. The owner asks a simple question: “How exactly do we calculate GST on an invoice?” You open InvoiceController to find the answer. The formula is inside store(), along with the invoice number logic, the amount checks and the code that prepares the response. The method is 80 lines long, and the GST formula is hidden in the middle.
Then the accountant asks for the same GST logic on the summary page. You copy it. A month later the rate changes for one product category, and you update only one of the two copies.
A controller should be like a receptionist. It receives the visitor, passes the job to the right person and gives back the answer. It should not do the work itself. In this lesson you will learn how to keep controllers thin by moving real work into service classes, and how to organize your folders so every class has an obvious home.
What a Fat Controller Looks Like
Here is a store() method that does too much. It reads input, applies a business rule, calculates GST, builds an invoice number and prepares the output, all in one place:
public function store(Request $request)
{
$client = $request->input('client');
$amount = (int) $request->input('amount');
if ($amount <= 0) {
abort(422, 'Amount must be greater than zero');
}
$gst = $amount * 0.18;
$total = $amount + $gst;
$number = 'INV-' . date('Y') . '-' . random_int(1000, 9999);
// Later: save to the database
// Later: email the invoice to the client
return [
'invoice' => $number,
'client' => $client,
'amount' => $amount,
'gst' => $gst,
'total' => $total,
];
}
Here $request->input('amount') simply reads the value named amount that was sent with the request. You will study the request object properly in the next chapter.
This looks harmless at 20 lines, but real projects keep adding to it. These are the problems that follow:
- The GST rule cannot be reused without copying it
- To test the calculation, you have to send a full web request
- The method has several reasons to change, so every change risks breaking something else
- New developers cannot see the business rules because they are buried in HTTP code
What Should a Controller Do?
A controller has a small set of jobs. It receives the request, passes the needed values to the code that does the real work, and returns a response. Everything else belongs somewhere else.
Controller keeps: Moves somewhere else:
- receive the request - business rules and calculations
- call the right class - talking to Razorpay or other APIs
- return view / JSON / redirect - database queries
- generating numbers, PDFs, emails
A good rule of thumb is that a controller method should fit on one screen, usually under ten or fifteen lines, and should read like a short list of instructions. Several of the other places have their own lessons later: Eloquent models handle database logic, Form Requests handle validation, and queued jobs handle slow work. In this lesson we focus on the place for business logic, which is a service class.
What Is a Service Class?
A service class is a plain PHP class that holds one area of your business logic. It has no connection to the web. It does not know about requests, responses or sessions, and it simply receives values and returns results. Because of that, you can use it from a controller, a command, a queued job or a test.
You already built one. GstCalculator from the last lesson is a small service. Now we will build a bigger one that handles invoices.
Creating the Service
Laravel can generate a plain class for you, in any folder you give it:
php artisan make:class Services/InvoiceService
This creates app/Services/InvoiceService.php with the namespace App\Services. Fill it in. Notice that the sample data from the controller moves here as well:
<?php
namespace App\Services;
class InvoiceService
{
public function __construct(private GstCalculator $gst)
{
}
public function all(): array
{
return [
1001 => ['client' => 'Sharma Traders', 'amount' => 12500],
1002 => ['client' => 'Patel Stationers', 'amount' => 8400],
1003 => ['client' => 'Iyer Electricals', 'amount' => 21000],
];
}
public function find(int $number): ?array
{
$invoice = $this->all()[$number] ?? null;
if ($invoice === null) {
return null;
}
return $this->withTotals($number, $invoice);
}
public function create(string $client, int $amount): array
{
$number = 'INV-' . date('Y') . '-' . random_int(1000, 9999);
return $this->withTotals($number, [
'client' => $client,
'amount' => $amount,
]);
}
private function withTotals(int|string $number, array $invoice): array
{
return [
'invoice' => $number,
'client' => $invoice['client'],
'amount' => $invoice['amount'],
'gst' => $this->gst->gst($invoice['amount']),
'total' => $this->gst->total($invoice['amount']),
];
}
}
The GST formula now exists in exactly one place, inside GstCalculator, and the invoice rules exist in exactly one place, inside InvoiceService. The service even uses another injected class. When Laravel builds InvoiceService, it sees that GstCalculator is needed and builds that too. This is the dependency injection you learned in the last lesson, working in a chain.
The Thin Controller
Now the controller becomes a simple coordinator:
<?php
namespace App\Http\Controllers;
use App\Services\InvoiceService;
use Illuminate\Http\Request;
class InvoiceController extends Controller
{
public function __construct(private InvoiceService $invoiceService)
{
}
public function index()
{
return $this->invoiceService->all();
}
public function show(int $invoice)
{
return $this->invoiceService->find($invoice) ?? abort(404);
}
public function store(Request $request)
{
return $this->invoiceService->create(
$request->input('client'),
(int) $request->input('amount'),
);
}
// create(), edit(), update() and destroy() stay as before
}
Compare this with the fat version. The store() method went from about twenty lines to three. It still does its own job: it takes values from the request and returns the result. The decision about what an invoice is, and how its totals are worked out, lives in the service.
Notice where abort(404) stayed. A 404 page is an HTTP response, so it belongs in the controller. The service only says “I found nothing” by returning null, and the controller decides how to respond. This division keeps services free of web details.
Organizing Your Folders
Laravel does not create an app/Services folder for you, and it does not force you to use one. The App\ namespace is mapped to the app/ directory through Composer’s autoloading, so any folder works as long as the namespace matches the path. The structure below is a common convention that works well for most projects:
app/
Contracts/
PaymentGateway.php
Http/
Controllers/
InvoiceController.php
Payments/
RazorpayCallback.php
Models/
Providers/
AppServiceProvider.php
Services/
GstCalculator.php
InvoiceService.php
Payments/
RazorpayGateway.php
Here is what each folder is for:
Http/Controllersholds controllers, and subfolders group them by area, likeAdmin/orPayments/Servicesholds classes with your business logicContractsholds interfaces, like thePaymentGatewayinterface from the last lessonModelsholds Eloquent models, which you will meet in the Eloquent chapter
The Namespace Must Match the Folder
The rule that makes autoloading work is simple: the namespace follows the folder path, and the file name matches the class name exactly. A class in app/Services/Payments/RazorpayGateway.php must start with:
namespace App\Services\Payments;
class RazorpayGateway
{
// ...
}
Capital letters matter. Windows does not care about them, but a Linux server does, so a mistake in capitalization can work on your laptop and break after deployment.
Grouping by Feature as the Project Grows
For a small app, one flat Services folder is fine. When you have many classes, group them in subfolders by feature, such as Services/Invoices/, Services/Payments/ and Services/Clients/. Do this only when the folder becomes hard to scan. Creating a deep structure on day one just makes small projects harder to read.
When Not to Create a Service
A service is a tool, not a rule. Do not create one for every controller.
- A simple list page that just returns records needs no service
- A method that is one or two lines is already thin
- A service that only passes a call to another class without adding any logic is extra work with no benefit
A good time to extract a service is when you notice one of three signs: the same logic appears in two places, a controller method keeps growing, or you want to test a rule without making a web request.
Common Mistakes
Mistake 1: Passing the Request Object into a Service
$this->invoiceService->create($request);
This ties the service to the web. You cannot call it from a command or a queued job, because there is no request there. Pass plain values instead, as we did with $client and $amount, and your service can be used anywhere.
Mistake 2: Wrong Namespace or Folder
If the file is in app/Services but the namespace says something else, Laravel cannot find the class:
Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Services\InvoiceService] does not exist.
Check three things: the file path, the namespace line at the top, and the use statement in the controller. All three must agree.
Mistake 3: Wrong Capital Letters in the File Name
A file called invoiceService.php may work on Windows, but on a Linux server it gives the same error as above. Name the file exactly like the class, InvoiceService.php, from the beginning.
Mistake 4: Creating One Giant Service
class InvoiceService
{
// 40 methods: invoices, clients, emails, PDFs, reports...
}
This only moves the fat controller into a fat service. Split by responsibility. For example, keep InvoiceService for invoice rules, and make separate classes for reports or reminders.
Mistake 5: Putting Web Code in a Service
Calls like abort(), redirect() and session handling are about the web response. If they sit in a service, that service can no longer be reused cleanly. Return data or null from the service, and let the controller choose the response.
Mistake 6: Extracting Too Early
If you wrap every small thing in a class, the project becomes a maze of tiny files. Extract when the code is repeated, long or hard to test, and not before.
Quick Summary
- A controller should receive the request, call the right class and return a response.
- A fat controller mixes business rules, calculations and HTTP code, which makes it hard to reuse and test.
- A service class is a plain PHP class that holds business logic and knows nothing about the web.
- Create one with
php artisan make:class Services/InvoiceServiceand inject it into the controller. - Services can depend on other services, and Laravel builds the whole chain automatically.
- Keep response decisions like
abort(404)in the controller, and return plain data from the service. - Laravel does not create
app/Services, but any folder works if the namespace matches the path. - File names must match class names exactly, including capital letters.
- Group classes by feature only when a folder grows too large.
- Do not create a service when a method is already short and simple.
What’s Next
That completes the Controllers chapter. You can now create plain, resource and single action controllers, receive dependencies and keep each controller thin. But we have used the request object only in passing so far. In the next chapter, you will study how data actually arrives in your app. The first lesson, The Request Object & Handling Input, shows how to read form values, query strings and headers safely.