How to Use API Resource Route in Laravel for RESTful APIs
In Laravel, you use
Route::apiResource to quickly create RESTful API routes for a controller. This method automatically sets up routes for index, show, store, update, and destroy actions without routes for create or edit views.Syntax
The Route::apiResource method defines multiple API routes for a controller following RESTful conventions. It accepts two main parameters:
- URI: The base URL path for the resource.
- Controller: The controller class handling the requests.
This method creates routes for index, show, store, update, and destroy actions only.
php
Route::apiResource('posts', PostController::class);
Example
This example shows how to define an API resource route for a PostController. It automatically creates routes for listing posts, showing a single post, creating, updating, and deleting posts.
php
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PostController; Route::apiResource('posts', PostController::class); // PostController methods: // index() - GET /posts // show($id) - GET /posts/{post} // store() - POST /posts // update($id) - PUT/PATCH /posts/{post} // destroy($id) - DELETE /posts/{post}
Output
Routes created:
GET /posts -> index
GET /posts/{post} -> show
POST /posts -> store
PUT/PATCH /posts/{post} -> update
DELETE /posts/{post} -> destroy
Common Pitfalls
Common mistakes when using apiResource include:
- Expecting routes for
createoreditviews, whichapiResourcedoes not generate because APIs usually don't serve HTML forms. - Not importing the controller class correctly, causing route registration errors.
- Defining conflicting routes manually that overlap with
apiResourceroutes.
php
<?php // Wrong: expecting create/edit routes Route::apiResource('posts', PostController::class); // Trying to access /posts/create will 404 // Right: Use Route::resource if you need create/edit views Route::resource('posts', PostController::class);
Quick Reference
API Resource Route Methods and HTTP Verbs:
| HTTP Verb | URI | Controller Method | Description |
|---|---|---|---|
| GET | /resource | index | List all resources |
| GET | /resource/{post} | show | Show a single resource |
| POST | /resource | store | Create a new resource |
| PUT/PATCH | /resource/{post} | update | Update an existing resource |
| DELETE | /resource/{post} | destroy | Delete a resource |
Key Takeaways
Use Route::apiResource to quickly create RESTful API routes without create/edit views.
apiResource generates routes for index, show, store, update, and destroy actions only.
Ensure your controller has methods matching the resource actions to avoid errors.
Do not expect HTML form routes like create or edit with apiResource; use Route::resource if needed.
Always import your controller class correctly when defining routes.