Often we need to handle subdomains with our Laravel application. Let’s take a look, how can we treat the routes dynamically and set up the subdomain with Valet and Forge.
Defining Subdomains in Our Routes
According to the documentation, we can easily set up subdomains in our route files. We can use a static subdomain, also we can use wildcards in our subdomains.
// Static subdomain Route::domain('app.yourapp.com')->group(function ($router) { // }); // Wildcard subdomain Route::domain('{user}.yourapp.com')->group(function ($router) { // });
As we see, we can you a route parameter like in a normal case, that we can use for example for route-model binding. Also, in some other cases, we can use only the static subdomain, for example when we just want to separate on part of our application from the rest of the app.
Dynamically Generate Subdomains
It’s not a good solution, that we hardcode the subdomain in the routes file since we use a different domain in local and production environment. We set up the current domain in the APP_URL .env variable. We can use that, to generate the proper subdomain depending on the environment, without hardcoding anything.
APP_URL=https://pinecode.test $domain = '{user}.' . parse_url(config('app.url'), PHP_URL_HOST); Route::domain($domain)->group(...);
Now we can change the APP_URL to anything because we parse it down to the host level, then we can append the fix subdomain or the wildcard parameter.
Faking Subdomains in Valet
Since Valet is directory based, we can easily create symbolic links to the application’s directory. When we hit the subdomain, Valet will load the symlink and we are ready to go. We can create symlinks easily:
ln -s example app.example
Using wildcards with Valet is not the best, but we can make a few symlinks to make the basic wildcard concept work.
Setting Up Subdomains in Forge
If you want to set up a full wildcard handling for a new site, you can just tick the “Allow Wildcard Sub-Domains“, then create the site.
But, if you want to add wildcards for an existing site, or add only one subdomain, you need to edit the Nginx configuration file. Select the site you want to edit, go down near to the footer and click on the “Files” > “Edit Nginx Configuration” menu.
Navigate to the 7th line, where your domains are defined. To allow wildcard subdomains, you just need to append a . to your domain:
# Before server_name example.com; # After server_name .example.com;
If you want to specify a subdomain next to your root domain, you just need to add it next to the existing one:
# Before server_name example.com; # After server_name example.com app.example.com;
After you saved the file and all the syntax checks passed, also, your DNS settings are good, you should have a working subdomain.