By the end of this lesson, the store() method that lends a book shrinks from 30 lines to 6. Its code moves into three new classes. The response to POST /loans stays exactly the same.
Architecture here means the rules for "which code lives where", so every class has one task. Remember the restaurant kitchen from the What is Laravel? lesson: the waiter doesn't cook, doesn't check the storeroom, and doesn't arrange the food on the plate. Someone checks the order, the cook cooks, the serving station puts the food on plates. A waiter who does everything is slow, makes mistakes, and is hard to replace. So is a controller that does everything. In this lesson, the controller is the waiter, not the cook as in the first lesson. Three new classes take the other tasks: a FormRequest is the order checker, the class BorrowBook is the cook, and a Resource is the serving station.
A fat controller
A fat controller is a controller that does everything by itself. This is store() for borrowing a book in the Library app, with all its code in one method:
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'book_id' => ['required', 'exists:books,id'],
]);
$book = Book::findOrFail($data['book_id']);
$loan = DB::transaction(function () use ($request, $book) {
$taken = Book::whereKey($book->id)->where('stock', '>', 0)->decrement('stock');
if ($taken === 0) {
throw ValidationException::withMessages(['book_id' => 'This book is out of stock.']);
}
return Loan::create([
'user_id' => $request->user()->id,
'book_id' => $book->id,
'due_at' => now()->addDays(14),
]);
});
BookBorrowed::dispatch($loan);
return response()->json(['data' => [
'id' => $loan->id,
'book' => $book->title,
'member' => $request->user()->name,
'due_at' => $loan->due_at->toDateString(),
]], 201);
}
This code runs and is correct. The problem is that one method knows five things at once:
- HTTP: the request and the 201 status.
- input rules:
book_idis required and must exist in thebookstable. - business rules, the library's own rules: there must be stock, and a loan lasts 14 days.
- the database: a transaction,
decrement, andcreate. - the JSON shape that is sent back.
If the admin wants to record a loan from an Artisan command, this logic can't be used. It is locked in a method that needs an HTTP request.
DB::transaction here makes two things happen together, or not at all: the stock goes down and the loan is recorded. The stock is checked inside the transaction, in the same query as decrement. whereKey($book->id) selects the row with this book's id. where('stock', '>', 0) only lowers the stock while there is stock left, and $taken holds the number of rows that changed. If $taken is 0, the code throws a ValidationException, and Laravel answers 422. If the stock were checked with an if before the transaction, two people borrowing the last copy in the same second could both pass that check, and the stock would become -1.
Step 1: validation into a FormRequest
Move the input rules into a FormRequest (a special class that holds validation rules, from the Validation lesson). Make it with php artisan make:request StoreLoanRequest. Laravel runs its rules before the controller is called, and answers 422 by itself when they fail. This is the class:
class StoreLoanRequest extends FormRequest
{
public function authorize(): bool
{
return true; // who may: the Policies & Authorization lesson
}
public function rules(): array
{
return ['book_id' => ['required', 'exists:books,id']];
}
}
The controller only replaces Request with StoreLoanRequest, then reads the validated book_id with $request->validated('book_id'). authorize() decides who may send this request. Watch out: the file make:request creates has an authorize() that returns false. If you forget to change it, every request is answered 403 | This action is unauthorized.
Step 2: business rules into an action class
The business rules and the database work move into a new class, app/Actions/BorrowBook.php. Make it with php artisan make:class Actions/BorrowBook:
class BorrowBook
{
public function execute(User $member, Book $book): Loan
{
$loan = DB::transaction(function () use ($member, $book) {
$taken = Book::whereKey($book->id)->where('stock', '>', 0)->decrement('stock');
if ($taken === 0) {
throw ValidationException::withMessages(['book_id' => 'This book is out of stock.']);
}
return Loan::create(['user_id' => $member->id, 'book_id' => $book->id, 'due_at' => now()->addDays(14)]);
});
BookBorrowed::dispatch($loan);
return $loan;
}
}
execute(User $member, Book $book)takes models (a member and a book), not aRequest. So a controller, an Artisan command, a queued job, and a test can all call it.- The controller gets a
BorrowBookobject through aBorrowBook $borrowBookparameter. The service container makes it (the Service Container lesson). - A class that does only one action, like
BorrowBook, is called an action. When several related actions sit in one class (for exampleLoanServicewithborrow(),return(),extend()), that class is called a service, usually inapp/Services. Both ways are common. Pick one, then use it in the whole project.
Step 3: the JSON shape into a Resource
The JSON shape moves into an API Resource (the API Resource lesson). Make it with php artisan make:resource LoanResource:
class LoanResource extends JsonResource
{
public function toArray(Request $request): array
{
return ['id' => $this->id, 'book' => $this->book->title, 'member' => $this->user->name, 'due_at' => $this->due_at->toDateString()];
}
}
The result
This is store() after the three steps:
public function store(StoreLoanRequest $request, BorrowBook $borrowBook): LoanResource
{
$book = Book::findOrFail($request->validated('book_id'));
return new LoanResource($borrowBook->execute($request->user(), $book));
}
From 30 lines down to 6. new LoanResource(...) wraps the data in "data". The resource also answers with status 201 by itself, because the loan it wraps was just created. These are the responses to three requests:
| Request body | Response, before and after the tidy-up |
|---|---|
{"book_id": 1} |
201 {"data":{"id":12,"book":"The Rainbow Troops","member":"Budi","due_at":"2026-10-23"}} |
{"book_id": 99} |
422 {"message":"The selected book id is invalid.","errors":{"book_id":["The selected book id is invalid."]}} |
{"book_id": 2}, This Earth of Mankind, stock 0 |
422 {"message":"This book is out of stock.","errors":{"book_id":["This book is out of stock."]}} |
Exactly the same. A refactor (tidying how the code is arranged) moves code without changing its behaviour. Run your tests (the Testing lesson) after every step to prove it.
Now each class is one layer, with its own task:
| Layer | May know | Doesn't need to know |
|---|---|---|
| Controller | the request coming in, the response going out | stock, transactions, the JSON shape |
StoreLoanRequest |
the input rules | how borrowing works |
BorrowBook |
business rules, the database, events | Request, response(), HTTP status codes |
LoanResource |
the JSON shape | where the data came from |
Folders and configuration
Each kind of code has its own folder:
| Kind of code | Folder |
|---|---|
| Eloquent models | app/Models |
| Controllers, FormRequests, Resources | app/Http/Controllers, app/Http/Requests, app/Http/Resources |
| Actions or services | app/Actions, app/Services |
| Events, listeners, jobs, policies | app/Events, app/Listeners, app/Jobs, app/Policies |
Values that differ per server (the database name, passwords, QUEUE_CONNECTION) live in the .env file, not in the code. You read them with env(), only in the files of the config/ folder. Everywhere else, use config():
// config/library.php
return [
'loan_days' => env('LOAN_DAYS', 14), // 14 when LOAN_DAYS isn't in .env
];
// in BorrowBook
'due_at' => now()->addDays(config('library.loan_days')),
config('library.loan_days') reads the loan_days key from the file config/library.php. Another example: env('DB_DATABASE', 'default') reads DB_DATABASE from .env, and the second argument is used when the value isn't there. On a server, php artisan config:cache stores all config in one file. After that, .env is no longer read, so env() outside config/ returns null.
⚠️ Code in the wrong layer
- An action that takes a
Request. Commands and jobs have no request, so the action can't be used there. Pass models or plain values as arguments. - Tidying up while changing behaviour. Move one step, run the tests, then continue. If the response changes, it isn't a refactor anymore.
env()outside theconfig/folder. The code works on your laptop, butenv()returnsnullon the server afterconfig:cache.- A layer for everything. A CRUD feature (create, read, update and delete data) of only 3 lines doesn't need an action, a service, and a repository (a special class for reading and saving data). Eloquent is already your database layer. Add a layer when the controller becomes fat, or when the logic is needed somewhere else.
- In the exercise, the route doesn't use the service. In the exercise, the logic lives in
OrderService. TheRoute::postroute only calls that service, then answers with status201.
TL;DR: A fat controller (a controller that does everything by itself) knows too much. Split it one step at a time. Validation moves into a FormRequest (make:request). Business rules (such as stock and loan length) move into an action class (for one action) or a service class (for several related actions), in app/Actions or app/Services. That class takes models, not a Request. The JSON shape moves into a Resource (make:resource). The controller only takes the request and returns the response, and the response stays exactly the same. Models live in app/Models. Values that differ per server live in .env, are read with env('NAME', 'default') only in the config/ folder, then are used in other code through config().
⚡ Validation moves into a FormRequest
Write:
class StoreLoanRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return ['book_id' => ['required', 'exists:books,id']];
}
}
Guess first: authorize() decides who may send this request. The file make:request creates fills it with return false;. If you forget to change it, what happens?
Every request is answered 403 | This action is unauthorized., even before the rules are checked, because false means nobody may send it.
Meaning: StoreLoanRequest is a FormRequest: a special class that holds validation rules, made with php artisan make:request StoreLoanRequest. Laravel runs its rules before the controller is called, and answers 422 by itself when they fail.
⚡ The controller is down to six lines
Write:
public function store(StoreLoanRequest $request, BorrowBook $borrowBook): LoanResource
{
$book = Book::findOrFail($request->validated('book_id'));
return new LoanResource($borrowBook->execute($request->user(), $book));
}
Meaning: StoreLoanRequest has already validated book_id. The business rules (stock, loan length) move into the BorrowBook action, a class that does one action: lending a book. That action takes models, not a Request, so a command, a job and a test can call it too. The JSON shape moves into LoanResource, an API Resource. The response stays exactly the same as before the tidy-up.
In the exercise, the logic lives in OrderService, and the Route::post route only calls that service, then answers with status 201.
⚡ Per-server values live in .env
Write:
// config/library.php
return [
'loan_days' => env('LOAN_DAYS', 14),
];
Meaning: Values that differ per server are kept in the .env file. env('LOAN_DAYS', 14) reads LOAN_DAYS from .env, or uses 14 when the value isn't there. Call env() only in the config/ folder. Everywhere else, use config('library.loan_days'), which reads loan_days from this file. After php artisan config:cache, .env is no longer read, so env() outside config/ returns null.