laravel

How To Do Laravel Subdomain Routing

Subdomain routing is the same as routing prefixing, but it’s scoped by subdomain instead of route prefix. There are two primary uses for this. First, you may want to present different sections of the application (or entirely different applications) to different subdomains. The following example shows you how to do this:

Route::group(['domain' => 'api.laravel-recipes.com'], function() {
    Route::get('/', function() {
        //
    });
});

Second, you might want to set part of the subdomain as a parameter, as illustrated in the following example. This is most often done in cases of multitenancy (think Slack or Harvest, where each company get’s their own subdomain).

Route::group(['domain' => '{account}.laravel-recipes.com'], function() {
    Route::get('/', function($account) {
        //
    });
   
    Route('/users/{id}', function($account, $id) {
        //
    });
});

Note that any parameters for the group get passed into the grouped routes’ methods as the first parameter(s).

Namespace Prefixes

When you are grouping routes by subdomain or route prefix, it’s likely their controllers have a similar PHP namespace. In the API example, all of the API routes’ controllers might be under an API namespace. By using the route group namespace prefix, as shown in the following examples, you can avoid long controller references in groups like API/ControllerA@index and API/ControllerB@index.

// App\Http\Controllers\ControllerA
Route::get('/', 'ControllerA@index');

// App\Http\Controllers\API\ControllerB
Route::group(['namespace' => 'API'], function() {
    Route::get('/', 'ControllerB@index');
})

Name Prefixes

Name prefixes don’t stop there. It’s common that route names will reflect the inheritance chain of path elements, so users/comments/5 will be served by a route named users.comments.show. In this case, it’s common to use a route group around all of the routes that are beneath the users.comments resources.

Just like we can prefix URL segments and controller namespaces, we can also prefix strings to the route name. With route group name prefixes, we can define that every route within this group should have a given string prefixed to its name. In this context, we’re prefixing users to each route name, then comments.

Route::group(['as' => 'users.', 'prefix' => 'users'], function() {
    Route::group(['as' => 'comments', 'prefix' => 'comments'], function() {
        // Route name will be users.comments.show
        Route:::get('{id}', function() {
            //
        })->name('show');
    });
});

About the author

Avatar

laravelrecipies