Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Change Connection Dynamically

How to change laravel's connection form controller but the connection information stored at database like database manager, my example :

I have a databases information on my database :

id, driver, database_name, username, password, host

so at my controller just call :

$connection = Database::find( 1 );
$users = new Users();
$users->setConnection( [
    'driver' => $connection->driver,
    'host' => $connection->host,
    'username' => $connection->username,
    'password' => $connection->password
] );
$users = $users->get();
like image 913
Yudi Yohanes Septian Gotama Avatar asked Feb 13 '17 06:02

Yudi Yohanes Septian Gotama


People also ask

How will you switch to a database Test_db?

To switch to the test_db database, use the \c command. postgres=# \c test_db; The syntax below should also work.


1 Answers

I will go for a helper here. Let's create one in app/Helpers/DatabaseConnection.php.

namespace App\Helpers;
use Config;
use DB;

class DatabaseConnection
{
    public static function setConnection($params)
    {
        config(['database.connections.onthefly' => [
            'driver' => $params->driver,
            'host' => $params->host,
            'username' => $params->username,
            'password' => $params->password
        ]]);

        return DB::connection('onthefly');
    }
}

And now somewhere in controller we try

use App\Helpers\DatabaseConnection;
... 

$params = Database::find( 1 );
$connection = DatabaseConnection::setConnection($params);
$users = $connection->select(...);

Note: Not tested. I hope it works or simply guide you

More info:

  • Using multi database: https://laravel.com/docs/5.3/database#read-and-write-connections

  • Setting configurations on the fly: https://laravel.com/docs/5.3/configuration#accessing-configuration-values

like image 78
EddyTheDove Avatar answered Oct 11 '22 08:10

EddyTheDove