Laravel Routing: Route Groups

Route Groups

Allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route.

Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the namespace method.

Route groups may also be used to handle sub-domain routing.

Middleware

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

    Route::get('user/profile', function () {
        // Uses first & second Middleware
    });
});

Middleware are executed in the order they are listed in the array.

Namespaces

Route::namespace('Admin')->group(function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
});

Sub-Domain Routing

Route::domain('{account}.myapp.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});

The sub-domain may be specified by calling the domain method before defining the group.

Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller.

Route Prefixes

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

Route Name Prefixes

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

Laravel Routing: Route Groups — Structure map

Clickable & Draggable!

Laravel Routing: Route Groups — Related pages: