Resource controllers help organize code by grouping related actions for a resource in one place. They make building web apps simpler and cleaner.
Resource controllers in Laravel
php artisan make:controller ResourceNameController --resource
This command creates a controller with methods for index, create, store, show, edit, update, and destroy.
You can register the controller routes with Route::resource('name', ResourceNameController::class);
php artisan make:controller ProductController --resource
Route::resource('products', ProductController::class);
<?php namespace App\Http\Controllers; use App\Models\Product; use Illuminate\Http\Request; class ProductController extends Controller { public function index() { return Product::all(); } public function show(Product $product) { return $product; } // Other resource methods here... }
This BookController handles all common actions for books. The routes created by Route::resource will call these methods automatically.
<?php namespace App\Http\Controllers; use App\Models\Book; use Illuminate\Http\Request; class BookController extends Controller { public function index() { return Book::all(); } public function create() { return 'Show form to create a book'; } public function store(Request $request) { $book = Book::create($request->all()); return response()->json($book, 201); } public function show(Book $book) { return $book; } public function edit(Book $book) { return 'Show form to edit book with id ' . $book->id; } public function update(Request $request, Book $book) { $book->update($request->all()); return response()->json($book); } public function destroy(Book $book) { $book->delete(); return response()->json(null, 204); } } // Route registration example: // Route::resource('books', BookController::class);
Resource controllers follow RESTful conventions, making your app predictable.
You can customize which methods to include by using only or except when registering routes.
Use route model binding to automatically get model instances in methods like show(Book $book).
Resource controllers group related actions for a resource in one controller.
Laravel can auto-generate routes for these actions with Route::resource.
This keeps your code organized and follows common web app patterns.