Ad

Set Database Connection And Language Dynamically In Laravel

- 1 answer

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.

Ad

Answer

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);
}
Ad
source: stackoverflow.com
Ad