editor@linuxhint.com

Guide To Laravel Route Groups

Guide To Laravel Route Groups

Often a group of routes share a particular characteristics – a certain authentication requirement, a path prefix or perhaps a controller namespace. Defining these shared characteristics again and again on each route not only seems tedious but also can muddy up the shape of your routes file and obscure some of the structures of your application.

Route groups allow you to group several routes together and apply any shared configuration settings once to the entire group to reduce this duplication. Additionally, route groups are visual cues to future developers (and to your own brain) that these routes are grouped together.

To group two or more routes together, you “surround” the route definitions with a group. In reality, you are actually passing a closure to the group definition and defining the grouped routes within that closure.

Route::group([], function() {
    Route::get('hello', function() {
    	return 'Hello';
    });
    Route::get('world', function() {
    	return 'World';
    });
});

By default a route group doesn’t actually do anything. There’s no difference between the example above and separating a segment of your routes with code comments. The empty array that’s the first parameter, however, allows you to pass a variety of configuration settings that will apply to the entire route group.

Middleware

Probably the most common use for route groups is to apply middleware to a group of routes. We use this with Laravel to authenticate users and restrict guest users from using certain parts of a site.

In the following example, we are creating a route group around the dashboard and account views and applying the auth middleware to both. In this example, it means that users have to be logged in to the application to view the dashboard or the account page.

Route::group(['middleware' => 'auth'], function() {
    Route::get('dashboard', function() {
    	return view('dashboard');
    });
    Route::get('account', function() {
    	return view('account');
    });
});