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?

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials