In this example, I will show you laravel 9 route group example from step by step. I will show you route prefix group in laravel 9. route middleware group in laravel, and route name group in Laravel 9. I will show you one after another with example code.

You know that Laravel route groups allow us to share route attributes, such as middleware, name, and prefix across a large number of routes without needing to define those attributes on each individual route.

laravel-9-route-group-example

Route Middleware Group

To assign a middleware or multiple middlewares to all routes within a group, we may use the middleware method before defining the group. Let's see the example code: 

<?php

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second middleware...
    });
 
    Route::get('/user/profile', function () {
        // Uses first & second middleware...
    });
});

 

Controllers Route Group

Assume we are going to use the same controller, we may use the controller method to define the common controller for all of the routes within the group.

<?php

use App\Http\Controllers\OrderController;
 
Route::controller(OrderController::class)->group(function () {
    Route::get('/orders/{id}', 'show');
    Route::post('/orders', 'store');
});

 

Route Prefixes Group

The prefix method can be used to prefix each route in the group within a given URI. For example, you may want to prefix all route URIs within the group with admin then we can define the route like that:

<?php 

Route::prefix('admin')->group(function () {
    Route::get('/users', function () {
        // Matches The "/admin/users" URL
    });
});

 

Route Name Prefixes

We can group route names also. The name method can be used to prefix each route name in the group with a given string. For example, we would like to prefix all of the grouped route's names with admin.

<?php 

Route::name('admin.')->group(function () {
    Route::get('/users', function () {
        // Route assigned name "admin.users"...
    })->name('users');
});

 

Now put together all of these routes within a group. How can we do that? See the example code:

<?php

use Illuminate\Support\Facades\Route;

Route::name('admin.')
    ->prefix('admin')
    ->middleware(['auth'])
    ->group(function () {

    Route::get('/users', function () {
        // Route assigned name "admin.users"...
        // Matches The "/admin/users" URL
        // This /users URI only for logged in users
    })->name('users');
});

 

Read also: Laravel 9 Route Controller Group Example

 

Hope it can help you.

Category : #laravel

Tags : #laravel , #laravel routing