Reputation: 337
I want to set DB_Database field in .env file according to need at runtime just to switch from one database to other. How to set it from controller ?? is there any way to set .env fields??
Upvotes: 0
Views: 2727
Reputation: 1835
Actually it's possible but it is not good idea. For switch between DB you can:
1.Add connection to your config/database.php
file:
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
],
2.Specify connection for DB request:
$users = DB::connection('mysql')->select(...);
$users = DB::connection('mysql2')->select(...);
Upvotes: 1