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!

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

Recent Premium Tutorials