aebersold aebersold - 3 months ago 18
PHP Question

Remove subdomain from URLs with Laravel 4

I use subdomain routing with a laravel 4.2 application. Here's my routes file:

Route::group(array('domain' => '{keyword}.example.com'), function() {
Route::get('/', 'FrontendHomeController@index');
});

Route::get('/', ['uses' => 'FrontendHomeController@index', 'as' => 'home']);
Route::get('hotels', ['uses' => 'FrontendHotelController@index', 'as' => 'hotelsearch']);
Route::get('hotel/{slug}/{id}', ['uses' => 'FrontendHotelController@detail', 'as' => 'hoteldetail']);
[...]


So I have a few pages which use subdomains like
keyword.example.com
,
another.example.com
. But most other pages are regular
example.com/page
URLs. This works fine so far. I generate the links for the navigation with Laravel url/route helpers, e.g.
{{ url('hotels') }}
or
{{ route('hotelsearch') }}
.

Now, on subdomain pages, the generated URL's have the subdomain included. E.g. on keyword.example.com,
{{ url('hotels') }}
generates
keyword.example.com/hotels
and not
example.com/hotels
.

I would like to remove the subdomains for all links generated with the
url()
or
route()
helpers, these helpers should always point to the root domain.


Is there a parameter or do I have to overwrite the helper methods somehow?

Answer

The url function in templates wraps Illuminate\Routing\UrlGenerator::to, which doesn't let you specify a domain, but you can use the same Route::group technique to encapsulate all your primary domain routes. (It does not require a wildcard, as shown in the documentation.)

Route::group(array('domain' => 'www.example.com'), function() {
    Route::get('hotels', ['uses' => 'FrontendHotelController@index', 'as' => 'hotelsearch']);
    // ...
});
Comments