繁体   English   中英

获取子域路由中的子域(Laravel)

[英]Get the subdomain in a subdomain-route (Laravel)

我正在构建一个子域指向用户的应用程序。 如何在路由之外的其他地方获取地址的子域部分?

Route::group(array('domain' => '{subdomain}.project.dev'), function() {

    Route::get('foo', function($subdomain) {
        // Here I can access $subdomain
    });

    // How can I get $subdomain here?

});

不过,我已经建立了一个混乱的解决方法:

Route::bind('subdomain', function($subdomain) {

    // Use IoC to store the variable for use anywhere
    App::bindIf('subdomain', function($app) use($subdomain) {
        return $subdomain;
    });

    // We are technically replacing the subdomain-variable
    // However, we don't need to change it
    return $subdomain;

});

我想在路由之外使用变量的原因是基于该变量建立数据库连接。

在提出这个问题后不久,Laravel 实现了一种新方法,用于在路由代码中获取子域。 它可以像这样使用:

Route::group(array('domain' => '{subdomain}.project.dev'), function() {

    Route::get('foo', function($subdomain) {
        // Here I can access $subdomain
    });

    $subdomain = Route::input('subdomain');

});

请参阅文档中的“访问路由参数值”。

$subdomain是在实际的Route回调中注入的,它在group闭包中是未定义的,因为Request还没有被解析。

我不明白为什么你需要在组闭包内使用它,在实际的Route回调之外。

如果您希望在解析Request在任何地方都可以使用它,您可以设置一个后过滤器来存储$subdomain值:

Config::set('request.subdomain', Route::getCurrentRoute()->getParameter('subdomain'));

更新:应用组过滤器来设置数据库连接。

Route::filter('set_subdomain_db', function($route, $request)
{
    //set your $db here based on $route or $request information.
    //set it to a config for example, so it si available in all
    //the routes this filter is applied to
    Config::set('request.subdomain', 'subdomain_here');
    Config::set('request.db', 'db_conn_here');
});

Route::group(array(
        'domain' => '{subdomain}.project.dev',
        'before' => 'set_subdomain_db'
    ), function() {

    Route::get('foo', function() {
        Config::get('request.subdomain');
    });

    Route::get('bar', function() {
        Config::get('request.subdomain');
        Config::get('request.db');
    });
});

以上不适用于 Laravel 5.4 或 5.6。 请测试这个:

$subdomain = array_first(explode('.', request()->getHost()));

使用宏的方式:

Request::macro('subdomain', function () {
    return current(explode('.', $this->getHost()));
});

现在你可以使用它:

$request->subdomain();

在路由调用中

$route = Route::getCurrentRoute();

现在您应该可以访问该路线的所有内容。 IE

$route = Route::getCurrentRoute();
$subdomain = $route->getParameter('subdomain');

像这样

Route::getCurrentRoute()->subdomain

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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