[英]Setting dynamic database in config during Login - Laravel
I'm trying to change the database connection on login based on the user's company. 我正在尝试根据用户的公司更改登录时的数据库连接。
Here my user has a company and its DB is companyA . 在这里,我的用户有一家公司,其DB是companyA 。
Below is my LoginController where I changed the connection: 下面是我更改连接的LoginController:
public function authenticated(Request $request,User $user)
{
\Config::set('database.connections.dynamicdb', array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => $user->company,
'username' => 'root',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'strict' => false,
'options' => [
\PDO::ATTR_EMULATE_PREPARES => true
]
));
return redirect()->intended($this->redirectPath());
}
So based on user->company
which is already defined in users table, the database name is changed. 因此,基于已在users表中定义的
user->company
,更改了数据库名称。
But somehow it doesn't work. 但不知怎的,它不起作用。 The error shown is
显示的错误是
No database selected.
没有选择数据库。
I tried below code to check if the values are set during login. 我尝试下面的代码来检查登录期间是否设置了值。
return \Config::get('database.connections.dynamicdb');
It showed all values set to my requirements. 它显示所有值都符合我的要求。 But when I check after login and reaching /home, the value of database in config is null.
但是当我在登录后检查并到达/ home时,config中的数据库值为null。
So what all changes should I do. 那么我应该做些什么改变呢。 Is my technique right?
我的技术对吗? Or is there any other solution for this.
或者还有其他任何解决方案。
In my Stock Model i have added the below lines: 在我的股票模型中,我添加了以下行:
protected $table = 'stocks';
protected $connection = 'dynamicdb';
And the query I'm running is just a get all query: 我正在运行的查询只是一个获取所有查询:
Stock::orderBy('tag_no','asc')->get()
Can anyone please tell me why this happens? 谁能告诉我为什么会这样? What should i do?
我该怎么办?
All requests are stateless so current request doesn't know that you set new config value in previous request. 所有请求都是无状态的,因此当前请求不知道您在先前的请求中设置了新的配置值。
You should call Config::set(...)
every time when you want to use dynamic database and set database name getting this value from User
instance. 每次要使用动态数据库并设置数据库名称从
User
实例获取此值时,应调用Config::set(...)
。
Setting above should be done using middleware and service provider . 应使用中间件和服务提供商完成上述设置。
Create new middleware and register it for web
middleware group (You may do this using the $middlewareGroups property of your HTTP kernel): 创建新的中间件并将其注册到
web
中间件组(您可以使用HTTP内核的$ middlewareGroups属性执行此操作):
protected $middlewareGroups = [
'web' => [
//...
\App\Http\Middleware\YourMiddleware::class,
],
//...
];
Then: 然后:
<?php namespace App\Http\Middleware;
class YourMiddleware
{
public function handle($request, Closure $next)
{
if (Auth::check()) {
$database_name = Auth::user()->company;
// Set your config here using $user->company
// ...
}
return $next($request);
}
}
If you must to set this value once (during authentication), you should combine above code and sessions to store this information between requests: 如果必须设置此值一次(在身份验证期间),则应将上述代码和会话组合在一起以在请求之间存储此信息:
session(['db_name' => $dbname]); // Set db_name and store it
$db_name = session('db_name'); // Get db_name from session
Read more about HTTP Sessions: https://laravel.com/docs/5.7/session#retrieving-data 阅读有关HTTP会话的更多信息: https : //laravel.com/docs/5.7/session#retrieving-data
First you need create new default db for connection and add to database.php like normal connection 首先,您需要为连接创建新的默认数据库,并像正常连接一样添加到database.php
'dynamicdb' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => 'default',
//others
],
next overriding model methods in Stock 库存中的下一个重写模型方法
protected $table = 'stocks';
protected $connection = 'dynamicdb';
/**
* @return string
*/
public function getTable()
{
$table = parent::getTable();
$database = config('database.connections.dynamicdb.database');
return starts_with($table, $database)
? $table
: $database . '.' . parent::getTable();
}
/**
* Set the table associated with the model.
*
* @param string $table
* @return $this
*/
public function setTable($table)
{
$database = config('database.connections.dynamicdb.database');
$this->table = starts_with($table, $database)
? $table
: $database . '.' . $table;
return $this;
}
Usage : \\Config::set('database.connections.dynamicdb.database',$user->company);
用法:
\\Config::set('database.connections.dynamicdb.database',$user->company);
or you can create helper for it Don't forget this method work only one connection and connected user have access all databases 或者您可以为它创建帮助程序不要忘记此方法仅工作一个连接,并且连接的用户可以访问所有数据库
Add Multiple DB in .env 在.env中添加多个DB
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=
ALT_DB_HOST=127.0.0.1
ALT_DB_PORT=3306
ALT_DB_DATABASE=database2
ALT_DB_USERNAME=root
ALT_DB_PASSWORD=
Edit config/database.php 编辑config / database.php
'connections' => [
'mysql' => [
......
],
'alt_mysql' => [
'driver' => 'mysql',
'host' => env('ALT_DB_HOST', '127.0.0.1'),
'port' => env('ALT_DB_PORT', '3306'),
'database' => env('ALT_DB_DATABASE', 'vibecloud'),
...
],
If Whole model used for ALT_MYSQL then 如果整个模型用于ALT_MYSQL那么
protected $connection = 'alt_mysql';
ELSE 其他
protected function stock_info() {
return \DB::connection('alt_mysql')->select('*')->from('stocks')->get();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.