Route::resource
The Route::resource
is a convenient method provided by the Laravel framework for creating CRUD routes in your application. It generates the standard set of routes for a resourceful controller, which can handle actions like creating, reading, updating, and deleting resources.
To use Route::resource
, you need to define the routes in your routes/web.php
file. Here's an example of how you can define a resource route for a PostController
:
Route::resource('posts', 'PostController');
This single line of code will generate the following routes:
Verb | URI | Action | Route Name
--------------|-----------------------|---------|--------------
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
These routes correspond to the common CRUD operations. For example, the GET /posts
route maps to the index
method in the PostController
, which typically shows a list of all posts. The POST /posts
route maps to the store
method, which handles the creation of a new post.
You can customize the generated routes by passing additional parameters to the Route::resource
method. For example, if you only want to generate routes for specific actions, you can use the only
parameter like this:
Route::resource('posts', 'PostController')->only(['index', 'show']);
This will generate only the index
and show
routes for the PostController
, excluding the other CRUD operations.
Alternatively, if you want to exclude certain routes, you can use the except
parameter:
Route::resource('posts', 'PostController')->except(['create', 'store']);
This will generate all the CRUD routes except for create
and store
.
By using Route::resource
, you can quickly define a set of routes for a resourceful controller without having to manually define each route individually.