Laravel Change Connection Dynamically

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


Thanks, EddyTheDove, I am using your solution which is great :) just to know how to select table name I am putting this

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['connection_name'] = 'onthefly';
    $params['dbname'] ='dbname';
    $params['driver'] = 'mysql';
    $params['host'] = 'localhost';
    $params['username'] = 'root';
    $params['password'] = '';
    $params['port'] = 3306;

$connection = DatabaseConnection::setConnection($params);
$getTableData = $connection->table('table_name')->where("column_name",'=','matchCondition')->get();