Subdomain Routing in Lumen

PHP

In Lumen, you can not group your subdomains so that you can not use wildcard subdomains which is one of the most annoying features of the Lumen. What people recommend is using more than one Lumen installations per subdomain or use Laravel with subdomain routing where you can use route paramaters like route URIs. However, with a simple control mechanism, you can decide what routes will be registered upon request. Probably, this is not the best method to implement, but it will work.

Let's say, you have a domain, mydomain.com with subdomains sub1.mydomain.com and sub2.mydomain.com. Moreover, let's also say you have Homestead installed where you have mydomain.app, sub1.mydomain.app, sub2.mydomain.app too. You can just edit your routes/web.php file like below where it will just load the routes with checking the subdomain name where the TLD is not important.

$routes = [
'mydomain' => function () use ($router) {
$router->get('/', ['as' => 'root', 'uses' => '[email protected]']);
$router->get('/about', ['as' => 'about', 'uses' => '[email protected]']);
},
'sub1' => function () use ($router) {
$router->get('/', ['as' => 'sub1', 'uses' => '[email protected]']);
},
'sub2' => function () use ($router) {
$router->get('/', ['as' => 'sub2', 'uses' => '[email protected]']);
}
];

if (isset($_SERVER['SERVER_NAME'])) {
list($subdomain, $domain) = explode('.', $_SERVER['SERVER_NAME'], 2);
    if (isset($routes[$subdomain])) {
$router->group([], $routes[$subdomain]);
}
}

With this configuration, where you don't have a nested subdomain name like make.my.subdomain.great.again.mydomain.com, you will handle all the requests. You can also set the middleware or change the prefix or namespace with modifying the group function's first parameter, empty array, like below.

$router->group(['prefix' => 'unbelievable'], $routes[$subdomain]);

Finally, if you have a better solution, I'd like to hear it as this is nothing but a simple hack.