Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set database connection and language dynamically in Laravel

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.

like image 331
ali Avatar asked Jan 05 '16 16:01

ali


1 Answers

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);
}
like image 106
jedrzej.kurylo Avatar answered Sep 24 '22 12:09

jedrzej.kurylo