简体   繁体   中英

Laravel prepending domain to named routes when using multiple domain routing

Since I couldn't comment on this other question because of reputation, I am asking it again.

Like the OP had posted, the routes in the web.php file for Laravel are as follows:

$loginRoutes = function () {

   Route::get('/', 'HomeController@index')->name('home');

};

Route::domain('domain1.com')->group($loginRoutes);
Route::domain('domain2.com')->group($loginRoutes);
Route::domain('localhost')->group($loginRoutes);

When calling named routes in blade, for example using route('home') the domain in the last line item of the code above is prepended to the link.

So if we are on domain1.com and a link in blade references route('home') the URL will have http://localhost prepended as the domain.

How can I avoid this without going through and hardcoding the urls?

Update I have hacked to together two approaches (posted as answers for others who may happen along here), but I hope someone can provide some clarity to a better way to handle this.

Here is how I am going to try solving it for now. This isn't elegant, but early testing seems to work.

Here is how the web.php file is going to shape up

$LARAVEL_HTTP_HOST = explode(':',$_SERVER['HTTP_HOST'])[0];

$loginRoutes = function () {

   Route::get('/', 'HomeController@index')->name('home');

};

if ($LARAVEL_HTTP_HOST == 'domain1.com') {

  Route::domain('domain1.com')->group($loginRoutes);

}
elseif ($LARAVEL_HTTP_HOST == 'domain2.com') {

  Route::domain('domain2.com')->group($loginRoutes);

}
elseif ($LARAVEL_HTTP_HOST == 'localhost') {

  Route::domain('localhost')->group($loginRoutes);

}
else
{

  // Some catch all routing here

}

An alternate answer below is only using conditionals. This seems to solve for the URL for named routes issue.

$LARAVEL_HTTP_HOST = explode(':',$_SERVER['HTTP_HOST'])[0];

if (in_array($LARAVEL_HTTP_HOST,array('domain1.com','domain2.com','localhost')))
{

  // Routes Here

}

Alright, posting yet a third option here.

Again, I am posting this option here for anyone that may come across the post. I am still looking for a viable and more elegant solution.

$LARAVEL_HTTP_HOST = explode(':',$_SERVER['HTTP_HOST'])[0];

$loginRoutes = function () {

   Route::get('/', 'HomeController@index')->name('home');

};

$allowedDomains = array(
    'domain1.com',
    'domain2.com',
    'localhost',
);

if (in_array($LARAVEL_HTTP_HOST,$allowedDomains))
{
    Route::group(['domain' => $LARAVEL_HTTP_HOST], $loginRoutes);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM