Labs ICT
Pro Login

Resource Controllers

One controller for all CRUD operations.

Resource Controllers

RESTful APIs follow predictable patterns. A resource controller maps all seven HTTP actions to controller methods in one clean line. No more defining each route individually.

This is one of Laravel's best features — it eliminates boilerplate and keeps your routes file clean.

Defining Resource Routes

Instead of writing seven separate route definitions, you use a single line:

use App\Http\Controllers\PostController;

Route::resource('posts', PostController::class);

This one line generates all seven routes:

GET    /posts          -> index    (list all)
GET    /posts/create   -> create   (show form)
POST   /posts          -> store    (save new)
GET    /posts/{post}   -> show     (show one)
GET    /posts/{post}/edit -> edit   (show edit form)
PUT    /posts/{post}   -> update   (save changes)
DELETE /posts/{post}   -> destroy  (remove)

You can see all your routes by running php artisan route:list.

Try it Yourself →

Selecting Specific Methods

Sometimes you don't need all seven methods. You can limit a resource route to specific actions:

Route::resource('posts', PostController::class)->only([
    'index', 'show', 'store',
]);

Route::resource('comments', CommentController::class)->except([
    'edit', 'update',
]);

This gives you fine-grained control over which actions are available.

Nested Resources

Resources often have parent-child relationships. A comment belongs to a post, so you nest them:

Route::resource('posts.comments', CommentController::class);

This generates routes like /posts/{post}/comments/{comment}. The parent ID is automatically available in your controller:

class CommentController extends Controller
{
    public function store(Request $request, Post $post)
    {
        $post->comments()->create($request->validated());

        return back();
    }

    public function destroy(Post $post, Comment $comment)
    {
        $comment->delete();

        return back();
    }
}

Laravel's route model binding automatically resolves both the post and comment models for you.