简体   繁体   中英

Getting subdomain within middleware web group in Laravel 5

picked up Laravel 5.2 some time ago but have never had to use subdomains before.

At the moment I have:

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

The thing is, if I want to grab a subdomain (if one exists), I don't then know how to pass it into the '/' route within the Middleware group as well. A lot of the subdomain routing tutorials don't seem to include/reference middleware web (as I have forms on the page and need this functionality also).

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

Doesn't work. I just want to get the subdomain (if exists), and stick it in through so I can recall it in my login view.

Here is the approach that I use. I wrap all routes inside the web middleware, and wrap most all other routes, with the exception of public pages like home , about , etc, in the auth middleware. From there, I can grab variable subdomains last, after any constant subdomains (if applicable).

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

It works well with my setup so I hope it helps you towards a solution.

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