In Laravel, a resource controller is a special type of controller designed to handle CRUD operations (Create, Read, Update, Delete) automatically.
Instead of manually defining routes and functions for every action, Laravel’s resource controller provides a clean and structured way to manage your application’s data operations with just one command.
A resource controller in Laravel is a controller that automatically creates methods for performing all common CRUD actions on a resource (like Product, User, Post, etc.).
When you create a resource controller, Laravel generates the following methods inside your controller file:
Method | Description |
|---|---|
| Display a list of all resources |
| Show form to create a new resource |
| Save a new resource to the database |
| Display a specific resource |
| Show form to edit an existing resource |
| Update a specific resource |
| Delete a specific resource |
php artisan make:controller ProductController --resource
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
return "Display all products";
}
public function create()
{
return "Show form to create a product";
}
public function store(Request $request)
{
return "Save product data";
}
public function show($id)
{
return "Show product details for ID: $id";
}
public function edit($id)
{
return "Edit product with ID: $id";
}
public function update(Request $request, $id)
{
return "Update product with ID: $id";
}
public function destroy($id)
{
return "Delete product with ID: $id";
}
}
use App\Http\Controllers\ProductController;
Route::resource('products', ProductController::class);
This single line automatically generates all seven routes for CRUD operations:
HTTP Method | URI | Controller Method | Action |
|---|---|---|---|
GET | /products | index | Show all products |
GET | /products/create | create | Show create form |
POST | /products | store | Save new product |
GET | /products/{id} | show | Show single product |
GET | /products/{id}/edit | edit | Show edit form |
PUT/PATCH | /products/{id} | update | Update product |
DELETE | /products/{id} | destroy | Delete product |
You can check these routes using:
php artisan route:list