Route Group within a Group

A real-life scenario: you want to have URLs like account/*** under the same Route group with a prefix, but some of them should be also restricted with Auth Middleware. No problem – you can create a Group within a Group!

So, for example, you want to have /account/register and /account/login without Auth Middleware (as in, available without login), but /account/edit needs to be available only to logged-in users.

The code in app/Http/routes.php would look something like this:

Route::group(['prefix' => 'account', 'as' => 'account.'], function () {

    Route::get('login', ['as' => 'login', 'uses' => 'AccountController@getLogin']);
    Route::get('register', ['as' => 'register', 'uses' => 'AccountController@getRegister']);

    Route::group(['middleware' => 'auth'], function () {
        Route::get('edit', ['as' => 'edit', 'uses' => 'AccountController@getEdit']);
    });

});

If you have that code in your routes.php file, you can call those routes in Blade view files like this:

<a href="{{ route('account.login') }}">Login</a>
<a href="{{ route('account.register') }}">Register</a>
<a href="{{ route('account.edit') }}">Edit Account</a>

By the way, have you noticed I assigned an ‘as’ => ‘account.’ parameter to the whole group? That’s a new small thing in Laravel 5.1 – you can save some bytes of code this way, don’t need to add that prefix to ‘as’ to every single route anymore. But please notice there’s a dot symbol at the end of ‘as’ – you can actually change it to whatever symbol you want, you’re not limited to the dot, it’s just the most common practice.

So, getting back to Route Group nesting, in short – you can actually have a group inside of another group, adding different rules (prefix, as, middleware etc.) for each of them. Pretty useful, huh?

Like our articles?
Check out our Laravel online courses!

2 COMMENTS

  1. I found this article helpful, thanks! Seems obvious to be able to nest route groups but it was not mentioned in the official Laravel documentation.

LEAVE A REPLY

Please enter your comment!
Please enter your name here