DEV Community

Bijay Kumar Pun
Bijay Kumar Pun

Posted on

3 1

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');
});
});

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

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.

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay