Laravel Resource Controllers

Laravel Resource Controllers

Resource controllers map the seven standard CRUD actions to a controller with a single route declaration.

1 - Generating a Resource Controller

php artisan make:controller PostController --resource --model=Post

2 - The Seven Resource Actions

| Verb      | URI                  | Action  | Route Name     |
|-----------|----------------------|---------|----------------|
| GET       | /posts               | index   | posts.index    |
| GET       | /posts/create        | create  | posts.create   |
| POST      | /posts               | store   | posts.store    |
| GET       | /posts/{post}        | show    | posts.show     |
| GET       | /posts/{post}/edit   | edit    | posts.edit     |
| PUT/PATCH | /posts/{post}        | update  | posts.update   |
| DELETE    | /posts/{post}        | destroy | posts.destroy  |

3 - Registering a Resource Route

// All seven actions at once
Route::resource('posts', PostController::class);

// Limit to specific actions
Route::resource('photos', PhotoController::class)->only(['index', 'show']);
Route::resource('comments', CommentController::class)->except(['destroy']);

4 - API Resource Routes (no create/edit views)

// routes/api.php
Route::apiResource('posts', PostController::class);

5 - Nested Resources

Route::resource('posts.comments', PostCommentController::class);
// Generates routes like: /posts/{post}/comments/{comment}