Laravel Controller Resource Routes Complete Guide
February 20, 2024
•
12 min read
Introduction
Laravel resource controllers provide a simple way to handle CRUD operations. They automatically generate routes for common actions, making your code cleaner and more maintainable.
Creating Resource Controller
Generate a resource controller:
php artisan make:controller PostController --resource
The generated controller includes:
// app/Http/Controllers/PostController.php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index() {}
public function create() {}
public function store(Request $request) {}
public function show(Post $post) {}
public function edit(Post $post) {}
public function update(Request $request, Post $post) {}
public function destroy(Post $post) {}
}
Resource Routes
Register resource routes:
// routes/web.php
Route::resource('posts', PostController::class);
This creates these routes:
GET /posts index posts.index
GET /posts/create create posts.create
POST /posts store posts.store
GET /posts/{post} show posts.show
GET /posts/{post}/edit edit posts.edit
PUT/PATCH /posts/{post} update posts.update
DELETE /posts/{post} destroy posts.destroy
Partial resources:
Route::resource('posts', PostController::class)->only(['index', 'show']);
Route::resource('posts', PostController::class)->except(['destroy']);
Nested Resources
// Nested resource routes
Route::resource('posts.comments', CommentController::class);
GET /posts/{post}/comments index
GET /posts/{post}/comments/create create
POST /posts/{post}/comments store
GET /posts/{post}/comments/{comment} show
GET /posts/{post}/comments/{comment}/edit edit
PUT/PATCH /posts/{post}/comments/{comment} update
DELETE /posts/{post}/comments/{comment} destroy
Controller handling nested resources:
public function index(Request $request, Post $post)
{
$comments = $post->comments;
return view('comments.index', compact('post', 'comments'));
}
API Resources
Use API resources for JSON responses:
php artisan make:resource PostResource
// app/Http/Resources/PostResource.php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class PostResource extends JsonResource
{
public function toArray(Request $request)
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'author' => $this->author->name,
'created_at' => $this->created_at->toISOString(),
];
}
}
public function index()
{
return PostResource::collection(Post::paginate(10));
}
Summary
Resource controllers and routes in Laravel provide an elegant way to handle CRUD operations. By leveraging nested resources and API resources, you can build clean, RESTful APIs and web applications.
For more information, check out our other tutorials on Route Model Binding and Form Request Validation.