Resource controllers with Route::resource
One artisan command and one route line give you a controller with all 7 conventional CRUD methods already stubbed out and wired to the right verbs and URIs. Here's how it fits together, method by method — and the leaner apiResource version for when there's no browser involved.
-
Generate the controller
The
--resourceflag stubs out all 7 CRUD methods with empty bodies, instead of the singleindex()you'd get from a plain controller. Add--modelto type-hint the methods against an existing Eloquent model.php artisan make:controller ProductController --resource --model=ProductThat creates
app/Http/Controllers/ProductController.phpwithindex,create,store,show,edit,updateanddestroyalready declared. -
Register the route
One line in
routes/web.phpregisters all 7 routes at once — the URIs, HTTP verbs and route names all follow REST conventions, so there's nothing left to configure.use App\Http\Controllers\ProductController; Route::resource('products', ProductController::class);Confirm what got registered with:
php artisan route:list -
The 7 methods it expects
Two of the seven —
createandedit— only exist to show HTML forms, which is why they drop out of the API version in the next step.Verb URI Method Route name GET /products index products.index GET /products/create create products.create POST /products store products.store GET /products/{product} show products.show GET /products/{product}/edit edit products.edit PUT/PATCH /products/{product} update products.update DELETE /products/{product} destroy products.destroy -
Fill in a couple of methods
Because the controller was generated with
--model=Product, the methods that take a{product}URI segment already type-hintProduct $product— Laravel resolves it from the route via route model binding, no manual lookup needed.public function index() { return Product::latest()->paginate(20); } public function store(Request $request) { $product = Product::create($request->validate([ 'name' => 'required|string|max:255', 'price' => 'required|numeric|min:0', ])); return redirect()->route('products.show', $product); } public function show(Product $product) { return view('products.show', compact('product')); } -
Building an API instead? Use apiResource
An API has no HTML forms, so it never needs
createoredit. The--apiflag generates a controller without those two, andRoute::apiResourceregisters only the remaining 5 routes.php artisan make:controller Api/ProductController --api --model=Productuse App\Http\Controllers\Api\ProductController; Route::apiResource('products', ProductController::class);That leaves exactly
index,store,show,updateanddestroy— the same verbs and URIs as the table above, minus the twoGETroutes that used to render forms.