Get a subdomain in a subdomain route (Laravel)

I am creating an application where a subdomain points to a user. How can I get the subdomain part of the address elsewhere than in the 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 built a messy job 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 a variable outside the route is to establish a database connection based on this variable.

+8
source share
5 answers

Shortly after this question was asked, Laravel introduced a new method to get the subdomain inside the routing code. It can be used as follows:

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

See "Accessing the route parameter value" in the documents .

+9
source

$subdomain is injected into the actual Route callback, it is undefined inside the group closure because Request has not yet been parsed.

I don’t understand why you need to have it inside the closure of the BUT group outside the actual Route callback.

If you want it to be available everywhere, ONLY after Request been parsed, you can configure the filter after saving the value of $subdomain :

 Config::set('request.subdomain', Route::getCurrentRoute()->getParameter('subdomain')); 

Refresh : apply a group filter to configure the connection to the database.

 Route::filter('set_subdomain_db', function($route, $request) { //set your $db here based on $route or $request information. //set it to a config for example, so it si available in all //the routes this filter is applied to Config::set('request.subdomain', 'subdomain_here'); Config::set('request.db', 'db_conn_here'); }); Route::group(array( 'domain' => '{subdomain}.project.dev', 'before' => 'set_subdomain_db' ), function() { Route::get('foo', function() { Config::get('request.subdomain'); }); Route::get('bar', function() { Config::get('request.subdomain'); Config::get('request.db'); }); }); 
+10
source

Above will not work in Laravel 5.4 or 5.6. Please check it:

 $subdomain = array_first(explode('.', request()->getHost())); 
+2
source

in route call

$route = Route::getCurrentRoute();

and now you should have access to everything that has a route. I.e

 $route = Route::getCurrentRoute(); $subdomain = $route->getParameter('subdomain'); 
0
source

You can do this for laravel 5:

 public function methodName(Request $request) { $subDomain = $request->route()->parameter('subdomain'); } 
-1
source

Source: https://habr.com/ru/post/954508/


All Articles