Step 1. In the env file write the code as below.
DB_HOST=127.0.0.1
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=
DB_HOST2=127.0.0.1
DB_DATABASE2=database2
DB_USERNAME2=root
DB_PASSWORD2=
Step 2. In the config/database.php write the code as below.
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'database' => env('DB_DATABASE', 'database1'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST2', '127.0.0.1'),
'database' => env('DB_DATABASE2', 'database2'),
'username' => env('DB_USERNAME2', 'root'),
'password' => env('DB_PASSWORD2', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
],
Step 3. In the model file add a line as below.
protected $connection = 'mysql2';
Step 4.
use App\Models\User;
class UsersController extends BaseController
{
class Order extends Model
{
protected $connection = 'mysql2';
protected $table = 'orders';
}
}
With Query Builder
$data1 = DB::connection('mysql')->table('users')->get(); // DB 1
$data2 = DB::connection('mysql2')->table('orders')->get(); // DB 2