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>