ArtisanTinkerer.github.io

Blog

View on GitHub

This is the second time I have had a requirement where I needed to allow users to connect to different databases, so I thought I should document it.

The idea came from Luke Evers

This is how I did it.

private function connect($dataSource)
{

$host = $dataSource->dataConnection->host;
$database = $dataSource->dataConnection->database;
$username = $dataSource->dataConnection->username;
$password = $dataSource->dataConnection->password;



Config::set("database.connections.temp", [
            "host" => $host,
            "database" => $database,
            "username" => $username,
            "password" => $password,
            "driver" => 'mysql',
            'collation' => 'utf8_unicode_ci'
        ]);

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

This creates a temporary connection called ‘temp’.

To get the data:

 private function getDataFromSource($dataSource){

        $connection  = $this->connect($dataSource);
        $records = DB::connection('temp')->select($dataSource->SQL);

        DB::purge('temp');

        return $records;
    }


Mick