Resource routes help you quickly create all the common routes for a controller in one line. This saves time and keeps your code clean.
0
0
Resource routes in Laravel
Introduction
When you have a controller managing a resource like users, posts, or products.
When you want to follow RESTful conventions for your web app routes.
When you want to avoid writing each route manually for actions like create, read, update, and delete.
When you want Laravel to automatically handle route naming and HTTP methods for you.
Syntax
Laravel
Route::resource('resource-name', ControllerName::class);
This single line creates multiple routes for standard actions.
The 'resource-name' is the URL segment, and the controller handles the logic.
Examples
Creates routes for posts with PostController handling actions.
Laravel
Route::resource('posts', PostController::class);
Creates all user-related routes like index, show, create, edit, update, and delete.
Laravel
Route::resource('users', UserController::class);
Creates only the index and show routes for products.
Laravel
Route::resource('products', ProductController::class)->only(['index', 'show']);
Creates all routes except the destroy (delete) route for orders.
Laravel
Route::resource('orders', OrderController::class)->except(['destroy']);
Sample Program
This code creates all standard routes for managing books. Laravel will map URLs like /books, /books/create, /books/{book}, etc., to the correct methods in BookController.
Laravel
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\BookController; Route::resource('books', BookController::class); // BookController should have methods: index, create, store, show, edit, update, destroy
OutputSuccess
Important Notes
Resource routes follow RESTful URL and HTTP method conventions automatically.
You can customize which routes to create using only() or except() methods.
Make sure your controller has the matching methods for the routes to work properly.
Summary
Resource routes create many routes in one line for common actions.
They follow RESTful patterns for URLs and HTTP methods.
Use only() or except() to control which routes are generated.