在Laravel 5中获取子域名在中间件Web组中

时间:2016-01-24 18:29:44

标签: php laravel laravel-5 laravel-routing

前一段时间拿起了Laravel 5.2,但之前从未使用过子域名。

目前我有:

Route::group(['middleware' => ['web']], function () {
    //Login/Logout
    Route::get('/', 'Auth\AuthController@getLogin');
    Route::get('/auth/login', 'Auth\AuthController@getLogin');
    Route::post('/auth/login', 'Auth\AuthController@postLogin');
    Route::get('/logout', 'Auth\AuthController@logout');
});

问题是,如果我想获取一个子域(如果存在),我就不知道如何将它传递到中间件组中的'/'路由。 许多子域路由教程似乎不包含/引用中间件web(因为我在页面上有表单,也需要此功能)。

Route::group(['middleware' => ['web']], function () {
    //Login/Logout
    Route::get('/', 'Auth\AuthController@getLogin');
    Route::get('/auth/login', 'Auth\AuthController@getLogin');
    Route::post('/auth/login', 'Auth\AuthController@postLogin');
    Route::get('/logout', 'Auth\AuthController@logout');
});

Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('/}', function ($account) {
        //Doesn't work
    });
});

不起作用。我只想获得子域名(如果存在),并将其粘贴在一起,以便我可以在登录视图中调用它。

1 个答案:

答案 0 :(得分:4)

这是我使用的方法。我将所有路由包装在web中间件中,并包裹大多数所有其他路由,但home中间件中的公共页面除外,如aboutauth等。从那里开始,我可以在任何常量子域(如果适用)之后最后获取可变子域。

// Encapsulate all routes with web middleware
Route::group(['middleware' => 'web'], function () {

    // Include auth routes
    Route::auth();

    // These routes are require user to be logged in
    Route::group(['middleware' => 'auth'], function () {

        // Constant subdomain
        Route::group(['domain' => 'admin.myapp.localhost.com'], function () {
            // Admin stuff
        });

        // Variable subdomains
        Route::group(['domain' => '{account}.myapp.localhost.com'], function () {

            // Homepage of a variable subdomain
            Route::get('/', function($account) {
                // This will return {account}, which you can pass along to what you'd like
                return $account;
            });
        });
    });

    // Public homepage
    Route::get('/', function () {
        // Homepage stuff
    });
});

它适用于我的设置,所以我希望它可以帮助您找到解决方案。

相关问题