When working locally with a local environment is really hard to use subdomains inside the application, this is because is not possible to do stuff like http://test.localhost or http://test.127.0.0.1, neither of them are valid domains. But, thankfully there are several services out there that solve this problem really easily.

For this example we will be using Laravel's built-in server and a service called lvh.me, this service redirects every requesto to our localhost's ip (127.0.0.1), therefore if we have an app running on port 8000, we can go into http://lvh.me:8000 and we should see exactly the same site as going to http://localhost:8000.

Before running our application we should have a way of receiving the request, let's just go to our routes.php file and insert the following code, here what we do is that any request that matches {account}.lvh.me we will grab the $account variable and dd() it.

Route::group(['domain' => '{account}.lvh.me'], function(){

    Route::get('/', function($account){
        dd($account);
    });

});

Further reading on how to do subdomain routing in the routes.php file

Now we just have to go over to our terminal and inside the project dir type:

php artisan serve --host 127.0.0.1  

Now we open our browser and go to http://test.lvh.me:8000 and we should see "test" printed in our screen. Pretty cool.

There is a small catch, if we only type php artisan serve it won't work as expected, this is because the artisan command serve will start the server with localhost as the host, therefore we can't access our app with 127.0.0.1 and then a service like lvh.me that points to this IP won't work. We do have to specify the host passing the option --host 127.0.0.1

Also there are several other services to accomplish exactly the same, one of them is http://lvho.st.

Happy Coding! :)


Comments? Something wrong in the post? or just want to contact me? Send me a tweet to @gpopoteur on twitter.