Laravel Sub-Domains

I recently implemented a simple blog on a sub-domain of my main site. However, I ran into several problems along the way.

Laravel sub-domain routing requires that you specify the full domain name, which can be tricky if you want the routing to work on multiple environments.

Sub-Domain Routing

One of the first problems I found was that the routing was falling through to the routes for the main site. I overcame this by making sure that these main routes were also surrounded by a route group with a domain key. So ended up with this:

Route::group(['domain' => 'blog.votemike.co.uk’], function () {
    //blog routes
});

Route::group(['domain' => 'votemike.co.uk’], function () {
    //main routes
});

Multiple Environments

The next problem was making this work work in multiple environments. My local version of my site is at votemike.app and similarly the blog is at blog.votemike.app. In order to get around this, I added a BASE_DOMAIN variable to my env file so that I ended up with:

$domain = env('BASE_DOMAIN');

Route::group(['domain' => 'blog.’ . $domain], function () {
    //blog routes
});

Route::group(['domain' => $domain], function () {
    //main routes
});

Homestead

Getting sub-domain routing working on Homestead is easy. Add another site in the Homestead.yaml as normal, pointing to the same directory as the main site. Provision Homestead, then add the subdomain to your hosts file. Easy.

Production

In order to get sub-domain routing working on production, I added an "A" Record to my DNS. I just needed to copy the information from the A Record for ‘www’ but instead use ‘blog’.