0
0
Laravelframework~5 mins

Route groups in Laravel

Choose your learning style9 modes available
Introduction

Route groups help organize routes that share common settings like middleware, prefix, or namespace. This keeps your route files clean and easier to manage.

You want to apply the same middleware to many routes, like authentication.
You want to add a common URL prefix to a set of routes, like '/admin'.
You want to group routes that share the same controller namespace.
You want to apply the same route name prefix to a group of routes.
You want to keep related routes together for better readability.
Syntax
Laravel
Route::group(['middleware' => 'auth', 'prefix' => 'admin'], function () {
    // Define routes here
});
You pass an array of options as the first argument to Route::group.
The second argument is a closure where you define the grouped routes.
Examples
This group applies the 'auth' middleware to the dashboard route.
Laravel
Route::group(['middleware' => 'auth'], function () {
    Route::get('/dashboard', function () {
        return 'Dashboard';
    });
});
This group adds '/admin' before the '/users' route URL, so the full URL is '/admin/users'.
Laravel
Route::group(['prefix' => 'admin'], function () {
    Route::get('/users', function () {
        return 'Admin Users';
    });
});
This group applies two middleware and a prefix to the settings route.
Laravel
Route::group(['middleware' => ['auth', 'verified'], 'prefix' => 'account'], function () {
    Route::get('/settings', function () {
        return 'Account Settings';
    });
});
Sample Program

This example creates a route group with 'auth' middleware and 'admin' prefix. It defines two routes: '/admin/dashboard' and '/admin/users'. Both require authentication.

Laravel
<?php

use Illuminate\Support\Facades\Route;

Route::group(['middleware' => 'auth', 'prefix' => 'admin'], function () {
    Route::get('/dashboard', function () {
        return 'Admin Dashboard';
    });

    Route::get('/users', function () {
        return 'User List';
    });
});
OutputSuccess
Important Notes

Route groups do not create new URLs themselves; they modify the routes inside them.

You can nest route groups to combine multiple settings.

Use route groups to keep your routes organized and avoid repeating code.

Summary

Route groups let you apply shared settings to many routes at once.

Common uses include middleware, URL prefixes, and namespaces.

They keep your route files cleaner and easier to read.