Laravel 5.1: Names for route groups

A small new feature in Laravel 5.1 - just for those who want to group their routes a little more properly. Now we can add a prefix not only to routes, but to the route groups as well.

The old way

Let's imagine we have a route group like this:
Route::group(['prefix' => 'user'], function()
{
    Route::get('/', function()
    {
        return view('user/main');
    });

    Route::get('profile', function()
    {
        return view('user/profile');
    });

});
Next step - we want to add names to the separate routes, to use them by names everywhere in the code:
Route::group(['prefix' => 'user'], function()
{
    Route::get('/', ['as' => 'user.main', function()
    {
        return view('user/main');
    }]);

    Route::get('profile', ['as' => 'user.profile', function()
    {
        return view('user/profile');
    }]);

});
So, at this point we have two named routes - user.main and user.profile, which we can use like this:
{{ link_to_route('user.main', 'User main') }}
{{ link_to_route('user.profile', 'User profile') }}

New in Laravel 5.1 - named groups

Now, to the point - a new feature of Laravel 5.1 (not 5.0): we can assign that user. prefix to the whole group, with the same "as" parameter. Like this:
Route::group(['prefix' => 'user', 'as' => 'user.'], function()
{
    Route::get('/', ['as' => 'main', function()
    {
        return view('user/main');
    }]);

    Route::get('profile', ['as' => 'profile', function()
    {
        return view('user/profile');
    }]);

});
The usage from views or from other files doesn't change - it's just more convenient grouping of routes in routes.php file. Notice another detail - we are not limited to dots at the end of the group name. We can put whatever symbol we want there: colon, comma, dash etc. Like this:
Route::group(['prefix' => 'user', 'as' => 'user-'], function()
{
    Route::get('/', ['as' => 'main', function()
    {
        return view('user/main');
    }]);

});
And then we will use this route like this:
{{ link_to_route('user-main', 'User main') }}
Not a huge win, but just for the sake of structure.

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 (1054 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials