Resource Controllers
Most things in Lendly, such as books, members and loans, need the same set of pages: list them, show one, create one, edit one, delete one. That is seven routes per thing, with predictable URIs and names. Laravel can register all seven in one line, and generate a controller with all seven methods waiting.
The rule
One Route::resource line gives seven routes, seven methods, seven names.
php artisan make:controller BookController --resource --model=BookRoute::resource('books', BookController::class);That line registers:
| Method | URI | Controller method | Name |
|---|---|---|---|
| GET | /books |
index |
books.index |
| GET | /books/create |
create |
books.create |
| POST | /books |
store |
books.store |
| GET | /books/{book} |
show |
books.show |
| GET | /books/{book}/edit |
edit |
books.edit |
| PUT/PATCH | /books/{book} |
update |
books.update |
| DELETE | /books/{book} |
destroy |
books.destroy |
The parameter is the singular {book}, and with --model=Book the methods are generated as show(Book $book) and so on, so route model binding just works.
Only some of them? Trim the list:
Route::resource('books', BookController::class)->only(['index', 'show']);
Route::resource('loans', LoanController::class)->except(['destroy']);An API with no HTML forms? Route::apiResource registers five, leaving out create and edit, which exist only to show forms.
Forms and PUT or DELETE. HTML forms can send only GET or POST. Laravel reads a hidden field to fake the rest:
<form method="POST" action="{{ route('books.destroy', $book) }}">
@csrf
@method('DELETE')
<button>Remove</button>
</form>The shortcut
Remember the pattern, not the table: collection URIs (/books) list and store; member URIs (/books/{book}) show, update and destroy; /create and /edit are only the forms.
Is it a form page or an action?
Saving is an action, not the form itself.
The trap is posting the edit form to books.edit. That route only shows the form. Saving goes to books.update.
Drills
Answer fast — trust the rule.
Which controller method handles POST /books?
Which two routes does Route::apiResource leave out?
How does an HTML form reach the destroy route?
What is the name of the route GET /members/{member}/edit from Route::resource('members', ...)?
Lendly members may view loans but never delete them through the site. Which line fits?
Remember
- One
Route::resourceline gives seven routes, seven methods, seven names. - Collection URIs list and store, member URIs show, update and destroy, and
/createand/editare the forms. - Trap: forms save to
update, notedit, and use@methodfor PUT and DELETE.
