Skip to main content
Tutorial Free

Wildcard Subdomain in Routes: Assign Subdomain for Every User

January 08, 2019
2 min read

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!

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.