【问题标题】:Laravel prepending domain to named routes when using multiple domain routing使用多域路由时,Laravel 将域添加到命名路由
【发布时间】:2021-02-08 03:50:08
【问题描述】:

由于名誉问题,我无法对this other question发表评论,我再次询问。

就像OP发布的那样,Laravel的web.php文件中的路由如下:

$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);

在 Blade 中调用命名路由时,例如使用 route('home') 时,上述代码最后一行中的域会添加到链接之前。

因此,如果我们在 domain1.com 上,并且刀片中的链接引用 route('home'),则 URL 将在前面添加 http://localhost 作为域。

如果不检查和硬编码网址,如何避免这种情况?

更新我已经破解了两种方法(发布为其他可能发生在这里的人的答案),但我希望有人可以提供一些清晰的更好的方法来处理这个问题。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    这是我现在尝试解决的方法。这并不优雅,但早期测试似乎有效。

    下面是 web.php 文件的结构

    $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
    
    }
    
    

    【讨论】:

      【解决方案2】:

      下面的替代答案仅使用条件。这似乎解决了命名路由问题的 URL。

      $LARAVEL_HTTP_HOST = explode(':',$_SERVER['HTTP_HOST'])[0];
      
      if (in_array($LARAVEL_HTTP_HOST,array('domain1.com','domain2.com','localhost')))
      {
      
        // Routes Here
      
      }
      

      【讨论】:

        【解决方案3】:

        好的,在这里发布第三个选项。

        再次,我在这里为可能遇到该帖子的任何人发布此选项。我仍在寻找可行且更优雅的解决方案。

        $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);
        }
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-14
          • 2015-05-10
          • 2020-01-04
          • 2020-08-11
          • 2019-08-17
          • 2018-03-01
          • 1970-01-01
          • 2017-05-22
          相关资源
          最近更新 更多