首页 > 解决方案 > Laravel 路由在 2 个环境中与子域一起使用

问题描述

我正在编写一个平台来生成子网站。

我有一条这样的路线,在本地运行良好:

//Website
Route::domain('{slug}.domain.test')->group(function () {
    Route::get('/','WebsitesController@show')->name('web_website_show');
});

我希望能够使其在生产(其他领域)中也能正常工作,所以我做到了:

//Website
Route::domain('{slug}.{domain}')->group(function () {
    Route::get('/','WebsitesController@show')->name('web_website_show');
});

在我的模板中:

<a href="{{ route('web_website_show',['slug' => $website->slug, 'domain' => Request::getHost() ]) }}">Website</a>

生成的 URL 看起来很神奇,但路由不起作用并将我带到主域的父页面。

我做错了什么?

谢谢

标签: laravelroutessubdomain

解决方案


在 Laravel 中使用这样的域路由有点痛苦。

最近在一个应用程序中,我从应用程序 URL 中解析了域部分,然后将其设置为配置值,如下所示:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        config([
            'app.domain' => parse_url(config('app.url'), PHP_URL_HOST),
        ]);
    }
}

然后,您可以在域路由中使用它:

Route::domain('{slug}.'.config('app.domain'), function () {
    // Subdomain routes that work in all environments
});

推荐阅读