DEV Community

Cover image for Practicing subdomain route in local environment with laravel
Md. Hazzaz Bin Faiz
Md. Hazzaz Bin Faiz

Posted on

Practicing subdomain route in local environment with laravel

Subdomain route is a less used feature in laravel as most of the laravel applications are hosted under one single domain. But the feature is available in laravel.

A friend of mine requested to write an article about how he can set up his local environment to test this subdomain routing, and I thought It will be better if I just document it ๐Ÿ™ƒ.

Setting UP DNS

First of all we need to set up DNS such a way that every subdomain points to one single host. A wildcard entry is enough for DNS server but wildcard is not supported in local host file.
We need to manually entry every subdomain in host file.
Host file path is different based on Operating System,
In windows : C:\Windows\System32\drivers\etc\hosts
In Linux : /etc/hosts
In Mac : /private/etc/hosts

We must have elevated privilege to edit host file, In windows we need to edit this file as Administrator, in linux use sudo or root user

As example I am using laravel.test as main domain,
In host file, add those entries laravel.test one.laravel.test two.laravel.test three.laravel.test

Setting up Route

In laravel, we just need to add a domain route to capture subdomains.
In, routes/web.php

Route::domain('{subdomain}.laravel.test')->group(function () {
    Route::get('/', function (string $subdomain) {
        return $subdomain;
Enter fullscreen mode Exit fullscreen mode

Now, if we start laravel app and brows http://laravel.test it will ignore subdomain route as it is not a subdomain, but if we brows http://one.laravel.test it will return only the subdomain.

Port number won't effect routing. If your application is running on port 8000, you can hit the subdomain route by browsing http://one.laravel.test:8000.

One thing to keep in mind, (from laravel official documentation)

In order to ensure your subdomain routes are reachable, you should register subdomain routes before registering root domain routes. This will prevent root domain routes from overwriting subdomain routes which have the same URI path.

Now you know what to do next, Artisan
Happy coding !!!

Top comments (4)

ripon52 profile image
Ripon Uddin

Repo example plz

hazzazbinfaiz profile image
Md. Hazzaz Bin Faiz

I haven't set up any repo for this. Just following those instructions will give you the expected results. Only thing to change is the route file.

robinamirbahar profile image


hazzazbinfaiz profile image
Md. Hazzaz Bin Faiz