Martney Acha
Martney Acha

Reputation: 3012

Change Database in Laravel 5.4

I have a code that is working but when I switch to different URL the connection I made is back at the default connection, what am I missing ?

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.

Upvotes: 1

Views: 1972

Answers (1)

Saiyan Prince
Saiyan Prince

Reputation: 4020

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

This is because, the .env file is not changed in which all of your application's configuration are stored.

Before changing..

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

In that same route, try to edit the .env file and then try to access all the other routes.

After accessing the /change-database route, it should reflect:

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

Or else, you will have to modify your application's code to match something like below: 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(...);

Upvotes: 4

Related Questions