DEV Community

Bijay Kumar Pun
Bijay Kumar Pun

Posted on

Subdomain Routing and Namespace Prefixes in Laravel

Excerpts from the book Laravel Up and Running by Matt Stauffer

Subdomain routing is like route prefixing yet with scope only within the subdomain.

Two primary uses of subdomain routing

  • Present different section of the application to different subdomain
  • Set part of the subdomain as parameter

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

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

The subdomain here is parameterized and will be passed as the first parameter to every grouped routes

Namespace Prefixes
Grouping routes by subdomain mean their controller may have similar PHP namespace.
Eg. for different APIs the namespace can be App\Http\Controllers\API\ControllerA
and for different subdomains, the namespace can be App\Http\Contollers\account\ControllerB etc.

These long controller references can be avoided with namespace prefixes

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

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

Name Prefix
Prefix can also be used for route groups. Route group name prefixes help define that every route within this group should have a given string prefixed to its name.
Ex.
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(){
//do something
}}->name('show');
});
});

Top comments (2)

Collapse
 
ivanpahlevi8 profile image
Ivan Indirsyah Pahlevi

Hi, how to open the subdomain in chrome?. because when i'm typing this(api.myapp.com) in my browser it show site not found

Collapse
 
moose_said profile image
Mostafa Said

You can do this by adding api.myapp.com in etc/hosts file in windows.