SyntaxStudy
Sign Up
Laravel Resourceful Routes and Route Model Binding
Laravel Beginner 1 min read

Resourceful Routes and Route Model Binding

Laravel's Route::resource() method registers all seven RESTful routes for a controller in a single line: index, create, store, show, edit, update, and destroy. This follows REST conventions and maps HTTP verbs to controller methods automatically. You can use Route::apiResource() to register only the five routes appropriate for a stateless API (omitting create and edit). Nested resources handle parent-child relationships between models. For example, Route::resource('posts.comments', CommentController::class) registers routes like /posts/{post}/comments/{comment}. The controller method receives both the parent and child as type-hinted parameters resolved through implicit model binding. Shallow nesting is a best practice for nested resources — it keeps only the routes that truly need the parent identifier nested, while standalone operations (show, edit, update, destroy) use the child's own URI. This produces cleaner URLs. You enable it with ->shallow() on the resource definition.
Example
<?php
// routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
use App\Http\Controllers\CommentController;

// Full resource: GET/POST /posts, GET/PUT/DELETE /posts/{post}, etc.
Route::resource('posts', PostController::class);

// API resource (no create/edit routes)
Route::apiResource('articles', \App\Http\Controllers\Api\ArticleController::class);

// Nested resource
Route::resource('posts.comments', CommentController::class)->shallow();

// Partial resource — only specific actions
Route::resource('photos', \App\Http\Controllers\PhotoController::class)
    ->only(['index', 'show']);

Route::resource('videos', \App\Http\Controllers\VideoController::class)
    ->except(['destroy']);

// Inspect all registered routes
// php artisan route:list

// Generated route names:
// posts.index   GET     /posts
// posts.create  GET     /posts/create
// posts.store   POST    /posts
// posts.show    GET     /posts/{post}
// posts.edit    GET     /posts/{post}/edit
// posts.update  PUT     /posts/{post}
// posts.destroy DELETE  /posts/{post}