What is resource controller in Laravel?

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.

1. What Is a Resource Controller?

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
index()
Display a list of all resources
create()
Show form to create a new resource
store()
Save a new resource to the database
show($id)
Display a specific resource
edit($id)
Show form to edit an existing resource
update(Request $request, $id)
Update a specific resource
destroy($id)
Delete a specific resource

2. How to Create a Resource Controller

php artisan make:controller ProductController --resource

3. Example of a Resource Controller

<?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";
    }
}

 4. Define Resource Routes

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


Comments