Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Today, I will give you an example of “How to create Controller route groups in Laravel 9”. So you can easily apply it with your 9 applications.
First, what we’re doing here, This is the example :
Route Groups is an essential feature in Laravel, which allows us to group all the routes, Routes Groups are beneficial when we want to apply the attributes to all the routes.
If we use route groups, we do not have to apply the attributes individually to each route this avoids duplication.
Laravel 9 Introduces the new features. The route group feature is one of them. Controller route group function, which is very useful for us to avoid defining the controller multiple times in the route file.
Routing Before in Laravel 9
use App\Http\Controllers\ProductController;
Route::get('/product', [ProductController::class, 'index']);
Routing in Laravel 9
use App\Http\Controllers\ProductController;
Route::controller(ProductController::class)->group(function () {
Route::get('/product/{id}', 'show');
Route::post('/product-store', 'store');
});
If a group of routes all utilizes the same controller, we may use the controller method to define the common controller for all of the routes within the group. Then, when defining the routes, we only need to provide the controller method that they invoke.
Let’s see the example below:-
Create a controller
php artisan make:controller ProductController
routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
Route::controller(ProductController::class)->group(function () {
Route::get('/create-product', 'createproduct');
Route::post('/store-product', 'storeproduct');
Route::get('/list-product', 'listproduct');
Route::get('/view-product/{id}', 'viewproduct');
Route::get('/edit-product/{id}', 'editproduct');
Route::post('/update-product/{id}', 'updateproduct');
Route::get('/delete-product/{id}', 'deleteproduct');
});
app\Http\Controllers\ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function createproduct(){
}
public function storeproduct(Request $request){
}
public function listproduct(){
}
public function viewproduct($id){
}
public function editproduct($id){
}
public function updateproduct(Request $request,$id){
}
public function deleteproduct($id){
}
}
Output :
Run Application : 127.0.0.1:8000/create-product
127.0.0.1:8000/view-product/8
We learned “How to create Controller route groups in Laravel 9”, I hope this article will help you with your Laravel application Project.
Also Read: How to create a model with migration in Laravel.