Dynamic custom domain and subdomain routing in Laravel

For an application that I’m building, I was faced with the problem of dynamic custom domain and subdomain. Meaning, each user and customer can have their own custom domain and a subdomain of the main site.
E.g. Oshane is a customer. Oshane can have:

To accomplish this, I googled.

The first thing I came across was the Laravel docs, of course. However, it wasn’t enough. After some amount of searching, I found two solutions, which I combined to form my solutions.

In the web.php file, add the following lines:


// Match my own domain
Route::group(['domain' => config('app.domain_url')], function() {
  Route::any('/', function()
    {
        return 'My own domain';
    });
});

// Match a subdomain of my domain
Route::group(['domain' => '{subdomain}.'.config('app.domain_url')], function() {
  Route::any('/', function()
    {
        return 'My own sub domain';
    });
});

// Match any other domains
Route::group(['domain' => '{domain}'], function() {
  Route::any('/', function()
    {
        return 'other domain';
    });
});

This solution was taken from Route group for any domain | Laravel.io. However, it didn’t truly solve the custom domain feature ['domain' => '{domain}'] in an elegant fashion.

Afterwards, I added a new config in the app.php file.

'domain_url' => preg_replace('#^https?://#', '', rtrim(env('APP_URL', 'http://localhost'),'/')),

Finally, I edited the App/Providers/RouteServiceProvider@boot method to look like the following:

public function boot()
    {
        //
        \Route::pattern('domain', '[a-z0-9.\-]+'); 
        parent::boot();
    }

The code above solved the issue that I was having with the first solution in an elegant manner. For more details, read Dynamic custom domain routing in Laravel | by Joe Lennon | Medium.

  1. Yes, it does.
  2. Each subdomains should be pointed to the main domain. You can create a CNAME record that points to your main domain, which is point to the root of the laravel app. You can also create a wildcard subdomain.