dbdxwb liked this thread
Hi @henockbarakael ! 👋
You can define multiple database connections in your config/database.php file.
Inside the connections
key you see multiple connections already defined. There, you can add another one by copy&pasting the existing connection (eg. for mysql):
'mysql2' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL_2'),
'host' => env('DB_HOST_2', '127.0.0.1'),
'port' => env('DB_PORT_2', '3306'),
'database' => env('DB_DATABASE_2', 'forge'),
'username' => env('DB_USERNAME_2', 'forge'),
'password' => env('DB_PASSWORD_2', ''),
'unix_socket' => env('DB_SOCKET_2', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
Then you can add the variables into your .env file like this (change the values to the correct ones):
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=laravel
DB_USERNAME_2=root
DB_PASSWORD_2=
DB_SOCKET_2=
DATABASE_URL_2=
Afterwards you can reference the new database connection like this:
$table_1 = DB::connection('mysql2')->table('transactions')->select('telco_reference','status')->get();
$table_2 = DB::table('money_transac')->select('telco_reference','status')->get();
$table_1
will contain the results from the mysql2
connection that you just defined and $table_2
will contain the results from the main/default connection that Laravel is also using.
Have a great day!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community