What you can do after this lesson
You will put request-handling code into controller classes, generate them with Artisan, and register the standard set of routes for a resource with one line. From here on, route files only describe URLs.
Why controllers
A closure in routes/web.php is fine for a one-liner. As the shop grows you will have dozens of routes, and putting them all in one file with their logic makes it unreadable and hard to maintain. A controller is a normal PHP class in app/Http/Controllers whose public methods each handle one kind of request. Related actions live together: everything about books in BookController.
Generating and writing a controller
php artisan make:controller BookController
php artisan make:controller HomeController --invokable INFO Controller [app/Http/Controllers/BookController.php] created successfully.
INFO Controller [app/Http/Controllers/HomeController.php] created successfully.In Laravel 13.42.0, the generated controller extends Controller (an empty base class in the skeleton) and has no methods; the --invokable one has an __invoke method. Fill them in. Pagelane Books does not have a database yet, so the controller holds a short list of sample books. This is temporary and the Eloquent lessons will replace it:
<?php
namespace App\Http\Controllers;
class BookController extends Controller
{
/** Temporary sample data; the database replaces it in the Eloquent lessons. */
private const BOOKS = [
1 => ['title' => 'The Quiet Harbour', 'author' => 'Mira Lindqvist', 'price_cents' => 1450],
2 => ['title' => 'Paper Lanterns', 'author' => 'Tomas Reyes', 'price_cents' => 1299],
3 => ['title' => 'Salt and Signal', 'author' => 'Ada Okafor', 'price_cents' => 1750],
];
public function index(): array
{
return array_values(self::BOOKS);
}
public function show(int $id): array
{
abort_unless(isset(self::BOOKS[$id]), 404);
return self::BOOKS[$id];
}
}The prices are whole cents (1450 means 14.50), a habit that avoids rounding errors with floats. The fictional authors and titles are invented for the course. abort_unless($condition, 404) throws a "not found" error when the condition is false. The home page uses a single-action controller:
class HomeController extends Controller
{
public function __invoke(): string
{
return config('app.name').' - '.config('shop.tagline');
}
}Pointing routes at controllers
Here is the new routes/web.php:
use App\Http\Controllers\BookController;
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;
Route::get('/', HomeController::class)->name('home');
Route::get('/books', [BookController::class, 'index'])->name('books.index');
Route::get('/books/{id}', [BookController::class, 'show'])
->whereNumber('id')
->name('books.show');The array [BookController::class, 'index'] means "call the index method of that class". ::class gives the full class name as a string, and your editor can refactor it. Check it:
php artisan route:list --except-vendor GET|HEAD / ..................................... home › HomeController
GET|HEAD admin ........................ admin.home › routes/web.php:15
GET|HEAD books .................... books.index › BookController@index
GET|HEAD books/{id} ................. books.show › BookController@show
GET|HEAD {fallbackPlaceholder} ..................... routes/web.php:20And with the server running:
curl -s localhost:8091/books/2
curl -s -o /dev/null -w "%{http_code}\n" localhost:8091/books/99{"title":"Paper Lanterns","author":"Tomas Reyes","price_cents":1299}
404Route parameters become method arguments, so show(int $id) receives the number from the URL. Here Laravel's route parameter {id} was matched by position.
Resource controllers
Most data has the same seven operations: list, show one, show a create form, store, show an edit form, update, delete. --resource generates a controller with all seven methods:
php artisan make:controller PhotoController --resourceThe seven methods are index, create, store, show, edit, update and destroy. One line of routing registers them all. For a resource called demo, route:list printed:
GET|HEAD demo ..................... demo.index › BookController@index
POST demo ..................... demo.store › BookController@store
GET|HEAD demo/create ............ demo.create › BookController@create
GET|HEAD demo/{demo} ................ demo.show › BookController@show
PUT|PATCH demo/{demo} ............ demo.update › BookController@update
DELETE demo/{demo} .......... demo.destroy › BookController@destroy
GET|HEAD demo/{demo}/edit ........... demo.edit › BookController@editThe registration was Route::resource('demo', BookController::class); (a throwaway test, not part of the shop). You can limit it with ->only([...]) or ->except([...]). Pagelane Books will use Route::resource('books', BookController::class) once its controller has all methods, in the Eloquent and forms lessons. For JSON APIs there is Route::apiResource, which leaves out create and edit because an API has no forms.
What goes in a controller
Keep controller methods thin: read input, call something that does the work (a model, an action class, a job), choose the response. Do not put long business rules, raw SQL or HTML strings into a controller. A good test of a method: can you read it in a few seconds? When it grows, extract a class.
Common mistakes
- Forgetting the
usestatement for the controller class inroutes/web.php, which gives "Class not found". - Typing the method name wrongly in
[BookController::class, 'idnex']. The error appears only when the URL is requested. - Naming a resource controller method differently, for example
list()instead ofindex(), soRoute::resourcepoints at a method that does not exist. - Putting everything in one giant controller. Split by topic.
- Ignoring missing records. Always handle "no such book" with
abort(404)or route model binding (the Eloquent lessons).
Exercise
Generate an invokable controller AboutController that returns the text Pagelane Books is a fictional shop used to teach Laravel., route it as GET /about with the name about, and check it with route:list.
Show one possible answer
php artisan make:controller AboutController --invokablepublic function __invoke(): string
{
return 'Pagelane Books is a fictional shop used to teach Laravel.';
}Route::get('/about', AboutController::class)->name('about');php artisan route:list --name=about then shows about › AboutController. Next: requests and responses.
Key points
- A controller is a class whose public methods handle requests, so routes stay short and logic is organised by topic.
- php artisan make:controller creates the file; --invokable makes a single-action controller and --resource adds the seven standard methods.
- Route::resource registers the seven conventional routes (index, create, store, show, edit, update, destroy) with names in one call.
- A route points at [BookController::class, 'index']; an invokable controller is referenced by its class name alone.
- abort_unless and abort stop a request with an HTTP error such as 404.