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.
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'); });
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.
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.
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.
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.
Way with macro:
Request::macro('subdomain', function () {
return current(explode('.', $this->getHost()));
});
Now you can use it:
$request->subdomain();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With