Laravel Resource Routes for Learners

You can write one line of code for defining a route for a CRUD operation, instead of writing different routes. This is called Resource Routes.

Why we need this?
Resource routes are a way of defining a set of routes that map to the various CRUD (Create, Read, Update, and Delete) operations for a resourceful controller.

1. Optimizes time and code.
2. Structured way.
3. Universal standard.

Resource routes in Laravel are defined using the Route::resource method. Here’s an example:

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

In this example, we define a set of resource routes for the PostController. Laravel will automatically generate routes for each of the CRUD operations, as well as a few additional routes:

Method 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

Even you can create a resource controller by one command.

php artisan make:controller PostController -r

In this controller, you will get all the functions written for you with an empty body.

In conclusion, resource routes in Laravel are a powerful and convenient way to define all the CRUD routes for a given resource in a single line of code. They provide a standardized way of naming and organizing your routes, making it easier to maintain and understand your application’s codebase.

By: Toukir Ibn Azad 0 0