Ad

Getting Subdomain Within Middleware Web Group In Laravel 5

- 1 answer

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\[email protected]');
    Route::get('/auth/login', 'Auth\[email protected]');
    Route::post('/auth/login', 'Auth\[email protected]');
    Route::get('/logout', 'Auth\[email protected]');
});

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\[email protected]');
    Route::get('/auth/login', 'Auth\[email protected]');
    Route::post('/auth/login', 'Auth\[email protected]');
    Route::get('/logout', 'Auth\[email protected]');
});

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.

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad