在 Laravel 5.4 中更改数据库

Change Database in Laravel 5.4

我有一个有效的代码,但是当我切换到不同的 URL 时,我建立的连接又回到了默认连接,我错过了什么?

Route::get('/change-database', function () {
    DB::purge('mysql');

    Config::set('database.connections.test.driver', 'mysql');
    Config::set('database.connections.test.host', 'localhost');
    Config::set('database.connections.test.username', 'root');
    Config::set('database.connections.test.password', '');
    Config::set('database.connections.test.database', 'fdis_two');

    Config::set('database.default', 'test');
    DB::reconnect('test');


    $connection= DB::connection()->getDatabaseName();
    return $connection;
});

它正在工作,但在转到不同的路由后,它又回到了默认连接。

It is working but after going to different routes its getting back to the default connection.

这是因为 .env 文件未更改,其中存储了您的所有应用程序配置。

改变之前..

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbName
DB_USERNAME=username
DB_PASSWORD=password

在同一路由中,尝试编辑 .env 文件,然后尝试访问所有其他路由。

访问/change-database路由后,应该反映:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=newDbName
DB_USERNAME=newUsername
DB_PASSWORD=newPassword

否则,您将不得不修改您的应用程序代码以匹配如下内容:Documentation

When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file:

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