13

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

2 Answers 2

30

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:

Sign up to request clarification or add additional context in comments.

3 Comments

Yes this is working, thank you, this is what i am looking for.
how do u choose table name?
I imagine life without this your solution. Great work. Thanks. life saver.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.