在Laravel中动态设置数据库连接和语言 [英] Set database connection and language dynamically in Laravel

查看:252
本文介绍了在Laravel中动态设置数据库连接和语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个域指向相同的 Laravel 应用程序.我想要的是每个人都可以连接到其自己的数据库并基于TLD加载其自己的语言文件.我可以在其中设置这些设置的文件是什么?我可以直接在配置文件中执行此操作,还是可以在加载配置之前在某些事件中执行此操作.

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.

我所拥有的是一个简短的函数,它将解析域并获取TLD,在快速验证之后,我们将基于该函数来知道将使用哪种数据库和语言.

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.

推荐答案

您可以使用中间件轻松地做到这一点-在此处查看一些文档: https://laravel.com/docs/master/middleware

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);
}

这篇关于在Laravel中动态设置数据库连接和语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆