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();
To switch to the test_db database, use the \c command. postgres=# \c test_db; The syntax below should also work.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With