如何在laravel 5.3中在运行时从控制器设置.env中的DB_Database字段?

时间:2016-10-19 14:24:56

标签: laravel laravel-5.3

我想在运行时根据需要在.env文件中设置DB_Database字段,只是为了从一个数据库切换到另一个数据库。如何从控制器设置?有没有办法设置.env字段?

1 个答案:

答案 0 :(得分:1)

实际上这是可能的但不是好主意。要在DB之间切换,您可以:

1.添加与config/database.php文件的连接:

'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.指定数据库请求的连接:

$users = DB::connection('mysql')->select(...);
$users = DB::connection('mysql2')->select(...);