This question already has an answer here:
I'm new in laravel and wondering how could I connect to multiple hosts and multiple databases in Laravel ?
if yes how i could do that dynamically ?
how to add new host connection dynamically ?
how to add new database connection dynamically ?
Config::set("database.connections.mysql", [
"host" => "...",
"database" => "...",
"username" => "...",
"password" => "...
]);
this is what i had found but i have no idea how to work further.
</div>
In your database.php, you can add multiple databases.
'mysql' => [
'driver' => 'mysql',
'host' => '',
'port' => '',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'mysql2' => [
'driver' => 'mysql',
'host' => '',
'port' => '',
'database' => '',
'username' => '',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
In order to use the databases, you can use a variable to use a specific connection, such as:
$db1 = DB::connection('mysql');
$db2 = DB::connection('mysql2');
Where mysql and mysql2 are the name you've defined your database by in your database.php
To run any raw SQL query, use:
$user1 = $db1->table('user_login')
->select('*')
->get();
$user2 = $db2->table('user_login')
->select('*')
->get();