How to Use Resource Route in Laravel: Simple Guide
In Laravel, use
Route::resource('name', ControllerName::class) to automatically create all RESTful routes for a controller. This single command sets up routes for index, create, store, show, edit, update, and destroy actions following Laravel conventions.Syntax
The Route::resource method registers multiple routes to handle typical CRUD operations for a controller. It takes two main parts:
'name': The base URI segment for the resource routes.ControllerName::class: The controller class that handles the requests.
This method automatically creates routes for index, create, store, show, edit, update, and destroy actions.
php
Route::resource('photos', PhotoController::class);
Example
This example shows how to define a resource route for a PhotoController. Laravel will create all standard routes for managing photos.
php
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PhotoController; Route::resource('photos', PhotoController::class); // This creates routes like: // GET /photos -> index // GET /photos/create -> create // POST /photos -> store // GET /photos/{photo} -> show // GET /photos/{photo}/edit -> edit // PUT/PATCH /photos/{photo} -> update // DELETE /photos/{photo} -> destroy
Output
Routes created:
GET /photos
GET /photos/create
POST /photos
GET /photos/{photo}
GET /photos/{photo}/edit
PUT/PATCH /photos/{photo}
DELETE /photos/{photo}
Common Pitfalls
Common mistakes when using resource routes include:
- Not creating the controller with the expected methods (index, create, store, etc.), which causes errors.
- Forgetting to import the controller class with
usestatement. - Using resource routes when only a few actions are needed, which can expose unwanted routes.
- Not naming route parameters correctly if customizing routes.
To fix exposing unwanted routes, use only or except options.
php
Route::resource('photos', PhotoController::class)->only(['index', 'show']); // or Route::resource('photos', PhotoController::class)->except(['create', 'edit']);
Quick Reference
| Method | URI | Action | Route Name |
|---|---|---|---|
| GET | /photos | index | photos.index |
| GET | /photos/create | create | photos.create |
| POST | /photos | store | photos.store |
| GET | /photos/{photo} | show | photos.show |
| GET | /photos/{photo}/edit | edit | photos.edit |
| PUT/PATCH | /photos/{photo} | update | photos.update |
| DELETE | /photos/{photo} | destroy | photos.destroy |
Key Takeaways
Use
Route::resource to quickly create all RESTful routes for a controller.Ensure your controller has the standard methods: index, create, store, show, edit, update, destroy.
Use
only or except to limit routes if you don't need all actions.Always import your controller class with a
use statement.Resource routes follow Laravel's naming conventions for easy route referencing.