Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 485
Martti Laine Avatar asked Sep 24 '13 13:09

Martti Laine


People also ask

How can I get subdomain name in Laravel?

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

What is subdomain routing in Laravel?

Subdomain routing is the same as routing prefixing, but it's scoped by subdomain instead of route prefix. There are two primary uses for this. First, you may want to present different sections of the application (or entirely different applications) to different subdomains.

How do I let PHP create subdomain automatically for each user?

We use the following code: $url=$_SERVER["REQUEST_URI"]; $account=str_replace(". yourdomain.com","",$url); This code just sets the $account variable the same as the subdomain.

What is route in Laravel?

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by your application's App\Providers\RouteServiceProvider . The routes/web.php file defines routes that are for your web interface.


2 Answers

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.

like image 163
Moshe Katz Avatar answered Oct 10 '22 17:10

Moshe Katz


Way with macro:

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

Now you can use it:

$request->subdomain();
like image 45
Ostap Brehin Avatar answered Oct 10 '22 16:10

Ostap Brehin