Laravel routing group for muliple domains with wil

2019-08-09 20:08发布

问题:

I have 3 domains which, on my local server, take the format:

  • mydomainfirst.local
  • mydomainsecond.local
  • mydomainthird.local

In my routes.php file, I have the following:

Route::group(array('domain' => '{domain}.{suffix}'), function() {

    Route::get('/', 'Primary@initialize');

});

The idea is to take the $domain variable in my controller and extract the first/second/third part from it, which works fine. However, now my site is online, this routing file no longer works and throws a Http-not-found exception. After a while, I have figured that the problem is that the domains have now taken the format mydomainfirst.co.uk. Because there are now 2 parts to the domain suffix, it seems I need to do this:

Route::group(array('domain' => '{domain}.{a}.{b}'), function() {

    Route::get('/', 'Primary@initialize');

});

To get it to work. Which is stupid. How can I tell it to just accept any suffix? Is there an 'anything' wildcard I can use?

I have tried a few things like this answer but it doesn't work with route groups.

EDIT: It seems the Enhanced Router package would at least enable me to add a where clause to the route group, but does it solve the problem of how to set a wildcard that will match an indeterminate number of segments? I need something like:

{domain}.{anything}

That will match both:

mydomainfirst.local AND mydomainfirst.co.uk

?

回答1:

Ok let me first say that the code of this package actually looks good and should work. Even if you can't get it running by installing you could take the files and use the code with your own service provider etc.

But there's also a kind of quick and dirty solution. (Actually the package does it pretty similar, but it looks a lot nicer ;))

First, here's how you can do it for one route:

Route::group(array('domain' => '{domain}.{tld}'), function(){
    Route::get('/', 'Primary@initialize')->where('tld', '.*');
});

So the where condition for the route group actually gets set on the individual route.

Of course you don't want to do this for every route inside that group so you can use a simple foreach loop:

Route::group(array('domain' => '{domain}.{tld}'), function($group){

    Route::get('/', 'Primary@initialize');

    foreach($group->getRoutes() as $route){
        $route->where('tld', '.*');
    }
});

Note: The loop needs to come after all routes. Otherwise they won't registered and therefore not returned with getRoutes()