Laravel Resource Controllers
A resource controller is a controller with one method for each common action on a resource. It covers listing, showing, creating, updating and deleting.
Make one
Artisan adds the --resource flag for a resource controller.
php artisan make:controller LibraryController --resourceCreate all seven routes
A resource controller covers all seven actions in one class.
Route::resource('books', LibraryController::class);List the items
The index method returns the full list.
public function index()
{
return 'All books';
}Example
use App\Http\Controllers\LibraryController;
Route::resource('books', LibraryController::class);
class LibraryController extends Controller
{
public function index()
{
return 'All books';
}
}Key points
- Resource controller: a controller with seven standard methods for one resource.
- Resource: a thing the app manages, such as a book.
- Use Route::resource to create all seven routes with one line.
- Use the index method to list every item in the resource.
In this example, one line creates all seven resource routes for books. The LibraryController class holds the seven standard methods. The index method returns the full list of books. A visit to /books shows the list.
Note
The seven methods are index, create, store, show, edit, update and destroy.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Route::resource('books', LibraryController::class) create?