Update Configuration
Laravel provides multiple database configurations and what you need to do is to add the additional configuration aside from the original one that they come by default. Within the "config/database.php" configuration you can create a new connection and for this example, I will be showing the one for "MySQL".
config/database.php
<?php return [ 'default' => env('DB_CONNECTION', 'mysql'), 'connections' => [ 'mysql' => [ '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_URL2'), 'host' => env('DB_HOST2', '127.0.0.1'), 'port' => env('DB_PORT2', '3306'), 'database' => env('DB_DATABASE2', 'forge'), 'username' => env('DB_USERNAME2', 'forge'), 'password' => env('DB_PASSWORD2', ''), 'unix_socket' => env('DB_SOCKET2', ''), '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_CA2'), ]) : [], ], ];
Update Environment Variable
You also need to update the environment variable located in ".env" file in your root project. Do note that your environment variable must be the same as the one you specified in the "config/database.php" file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=root DB_USERNAME=myappdb DB_PASSWORD= DB_CONNECTION2=mysql DB_HOST2=127.0.0.1 DB_PORT2=3306 DB_DATABASE2=root DB_USERNAME2=myappdb2 DB_PASSWORD2=
Defining Schema
When defining table schema then you can specify the "connection" like below. Running the migrate column will create a table inside "mysql2" database.
<?php Schema::connection('mysql2') ->create('posts', function($table) { $table->increments('id'): });
Query Builder
When querying up the database, you can also specify the "connection" on to which the database to query.
<?php $users = DB::connection('mysql2') ->table('posts') ->first();
Eloquent Model
For the eloquent model, you can specify the connection directly from the model itself and it's as follows.
<?php class Post extends Eloquent { protected $connection = 'mysql2'; }
Leave a reply