Yudi Yohanes Septian Gotama Yudi Yohanes Septian Gotama - 1 month ago 23
PHP Question

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();

Answer Source

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: