PeterTheLobster
PeterTheLobster

Reputation: 1395

How to generate proper links using Laravel subdomain routing?

I am trying to add dynamic subdomain routing to a project. The problem I am having is generating links between the subdomains and the top level domain.

First I tried creating the routes this way:

Route::get('/','MainController@getHome')->name('home');

Route::group(array('domain' => '{subdomain}.localhost/public'), function() {
    Route::get('/','MainController@getHomeNew' )->name('home_mew');
});

My assumption was, that generating the links in the following way would lead me to the proper route:

//I assumed this would always generate a link to the root of 'localhost/public/':
route('home'); 

//And that this would always take me to a sub domain root e.g. 'cats.localhost/public/':
route('home_new', ['subdomain' => 'cats']); 

When on a top-level domain page using route('home_new', ['subdomain' => 'cats']); properely generates a link to 'cats.localhost/public'.

The problem is that once I am at cats.localhost/public and I use route('home') I still get redirected to cats.localhost/public

So I tried wrapping the top level domain routes in a group of its own:

Route::group(array('domain' => 'localhost/public'), function() {
    Route::get('/','MainController@getHome')->name('home');
});

Route::group(array('domain' => '{subdomain}.localhost/public'), function() {
    Route::get('/','MainController@getHomeNew' )->name('home_mew');
});

This however results in a 404 error regardless of whether I go to the top domain root or a subdomain root.

How can I generate links in a subdomain that would lead to the top level domain instead? Can this be done without for example relying on redirecting?

Upvotes: 1

Views: 2065

Answers (1)

PeterTheLobster
PeterTheLobster

Reputation: 1395

Well I solved the problem by modifying my c:/windows/system32/drivers/etc/hosts file and adding this line:

127.0.0.1 myapp.com subdomain.myapp.com anothersub.myapp.com

Then I changed C:\xampp\apache\conf\extra\httpd-vhosts configuration file and added:

<VirtualHost *:80>
    ServerName www.myapp.com
    ServerAlias myapp.com
    DocumentRoot C:\xampp\htdocs\myapp\_src\public
</VirtualHost>

And modifying my routes thusly:

Route::group(array('domain' => 'myapp.com'), function()
{
    Route::get('/','MainController@getHome')->name('home');
});

Route::group(array('domain' => '{subdomain}.myapp.com'), function() {
    Route::get('/','SubController@getHome' )->name('home_new');
});

Upvotes: 0

Related Questions