Set database connection and language dynamically i

2019-05-08 18:35发布

I have 3 domains pointing at the same Laravel application. What I want is for each one to connect to its own database and load its own language file based on the TLD. What is the file where I could set up these settings? Can I do it in the configuration file directly or maybe some event before the configuration is loaded.

What I have is a short function that will parse the domain and get the TLD, based on which, after a quick validation, we would know what database and language will be used.

1条回答
Summer. ? 凉城
2楼-- · 2019-05-08 19:08

You can easily do that with a middleware - see some docs here: https://laravel.com/docs/master/middleware

You need a middleware that would be run for all requests before controllers are executed. This middleware should configure application locale and connection used based on the domain and then execute the request. Something similar to the following logic should do the trick:

public function handle($request, Closure $next)
{
  $host = $request->getHost();

  //do your logic that determines the language and connection to use based on TLD
  $language = $this->getLanguageForTld($host);

  //set connection used
  Config::set('database.default', $language);

  //set application locale
  App::setLocale($language);

  return $next($request);
}
查看更多
登录 后发表回答