While working with more advanced Laravel applications, you come to question how to work with more advanced routing circumstances. Laravel 4 gave a ton of features with the more advanced features in route groups, but there still are a few things that are arguably lacking.
One thing I found was a lacking support for sites with multiple Top Level Domains (site.com, site.org). This may not seem like a big deal for you, but accompanying a development setup that uses Multicast DNS to map site.local to your development machine may have you thinking again. For multi-tennant sites using subdomains, this matching is huge because you no longer have to temporarily redirect requests to site.com to your local machine during testing.
So, now on with the show.
It turns out that while it would be nice to match wildcard TLDs with a route group such as
Route::group(['domain' => '{user}.site.*'], function()
{
// Routes in this group
});
This unfortunately does not work. However after a bit of tinkering, it is relatively easy to make something just as beautiful, fast, and flexible.
- Warning,* this does use a regex so don't freak out, I will explain what everything is doing.
We are going to create a helper function called get_tld
to grab the TLD for a single request.
if ( ! function_exists('get_tld'))
{
function get_tld()
{
$matches = array();
preg_match('/site(.*)/', Request::root(), $matches);
$tld = $matches[1];
return $tld;
}
}
What this is doing is checking the reqest root url to see if it matches our site.*
. But then we grab the .com
or .local
and return it ($matches[0]
has the complete Regex matching phrase).
Now our route group can look like this:
$tld = get_tld();
Route::group(['domain'] => 'sub.site'.$tld], function()
{
// Routes in this group
});
This becomes even more useful as you can use it for those times when you are working from a localhost address and don't have the ability to use subdomains. I will be covering subdomain/non-subdomain routing duplicity techniques in a future post.