Search code examples
phplaravellaravel-4

Get the subdomain in a subdomain-route (Laravel)


I'm building an application where a subdomain points to a user. How can I get the subdomain-part of the address elsewhere than in a route?

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

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

    // How can I get $subdomain here?

});

I've built a messy work-around, though:

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;

});

The reason I want to use the variable outside a route is to establish a database-connection based on that variable.


Solution

  • Shortly after this question was asked, Laravel implemented a new method for getting the subdomain inside the routing code. It can be used like this:

    Route::group(array('domain' => '{subdomain}.project.dev'), function() {
    
        Route::get('foo', function($subdomain) {
            // Here I can access $subdomain
        });
    
        $subdomain = Route::input('subdomain');
    
    });
    

    See "Accessing A Route Parameter Value" in the docs.