Wildcard Subdomain in Routes: Assign Subdomain for Every User

In modern multi-tenancy systems, it’s pretty popular to give a specific sub-domain for every user or company, like laraveldaily.slack.com. How to handle these subdomains in Laravel routes?

The code in routes/web.php is pretty straightforward:

Route::domain('{company_name}.workspace.com')->group(function () {
    Route::get('users', 'UsersController@index');
});

So {company_name} could be any value (of course, you need to configure it in your domain DNS records, too), and then this will come as a parameter variable to the Controller, with the same name.

public function index($company_name)
{
    $company = Company::findOrFail($company_name);
    $users = User::where('company_id', $company->id)->get();
    return view('users.index', compact('users'));
}

Wait, But.. How to Setup Local Environment?

With this routes file, we have a problem. Then we need to configure our local server to have specific workspace.com domain? Don’t worry, there’s a cure for that, we can make even that domain a variable:

Route::domain('{company_name}.' . env('SITE_URL', 'workspace.com'))->group( // ...

So now the whole string would consists of two variables – subdomain and main domain, both configurable.

For your local environment, you can set up something like workspace.test domain, and then add this into your .env file:

SITE_URL=workspace.test

If Laravel doesn’t find any value for SITE_URL, it will default to workspace.com.

That’s it, good luck with your multi-tenancy projects!

Like our articles?
Check out our Laravel online courses!

3 COMMENTS

  1. Ho, great article. Make me think about, how about having a complet domain for each of the tenant ? Something like mysite1.com for user1, mysite2.com for user2. Is this feasible ?

    • Not really, you can’t register new domains that flexibly, that’s not how domain registration works. It’s not about Laravel or code, it’s domain system.

  2. good article (:
    I have applied all of the items and changed apache like

    ServerName website.com
    ServerAlias *.website.com
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/host/blog1019

    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all

    and also my hosts file
    0.0.0.0 website.com
    0.0.0.0 *.website.com
    .i work laravel5.7 ubuntu on localhost .. what is miss ??

LEAVE A REPLY

Please enter your comment!
Please enter your name here