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.
Below is my LoginController where I changed the connection:
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.
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.
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?
authenticated()is called. As soon as yourredirect()happens at the end of that method, that generates a new request, and the default config is loaded again.