Laravel Multiple Database Connections

1. config/database.php

 'mysql1' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            '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'),
            ]) : [],
        ],

        'mysql2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            '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', ''),
            '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'),
            ]) : [],
        ],

 

 

2. .env

 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_multiple_database1
DB_USERNAME=root
DB_PASSWORD=

DB_CONNECTION_2=mysql
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=laravel_multiple_database2
DB_USERNAME_2=root
DB_PASSWORD_2=

 3. connection setting

$table1 = DB::connection('mysql1')->table('desa')->get()
->each(function ($item) {
DB::table('desa')->insert([
'id_desa' => $item->id_desa,
'id_prov' => $item->id_prov,
'id_kab' => $item->id_kab,
'id_kec' => $item->id_kec,
'nm_desa' => $item->nm_desa,
'st_desa' => $item->st_desa,

]);
});

 

$table2 = DB::connection('mysql2')->table('desa')->get()
->each(function ($item) {
DB::table('desa')->insert([
'id_desa' => $item->id_desa,
'id_prov' => $item->id_prov,
'id_kab' => $item->id_kab,
'id_kec' => $item->id_kec,
'nm_desa' => $item->nm_desa,
'st_desa' => $item->st_desa,

]);
});

 in this case i wanna insert all table (looping using each method) data from mysql to oracle database using mysql1 and mysql2 connection by default oracle database connection

https://codelapan.com/post/how-to-use-multiple-database-connections-in-laravel-8