Laravel Multiple Database configuration
Step 1: Configure Database Connections
// config/database.php
'connections' => [
'mysql' => [
'driver' => 'mysql',
'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', ''),
// ...
],
'second_db' => [
'driver' => 'mysql',
'host' => env('SECOND_DB_HOST', '127.0.0.1'),
'port' => env('SECOND_DB_PORT', '3306'),
'database' => env('SECOND_DB_DATABASE', 'forge'),
'username' => env('SECOND_DB_USERNAME', 'forge'),
'password' => env('SECOND_DB_PASSWORD', ''),
// ...
],
// Add more database connections as needed
],
Step 2: Set Environment Variables
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
SECOND_DB_CONNECTION=mysql
SECOND_DB_HOST=127.0.0.1
SECOND_DB_PORT=3306
SECOND_DB_DATABASE=second_database
SECOND_DB_USERNAME=second_username
SECOND_DB_PASSWORD=second_password
Step 3: Create Models
php artisan make:model User -m
php artisan make:model Product -m
This instruction creates model and migration files for each model. Ensure that you define the connection in the generated model files:
// app/Models/User.php
protected $connection = 'mysql';
// app/Models/Product.php
protected $connection = 'second_db';
Step 4: Run Migrations
php artisan migrate
php artisan migrate --database=second_db
Step 5: Query Data from Multiple Databases
use App\Models\User;
use App\Models\Product;
// Retrieve users from the 'mysql' database
$users = User::all();
// Retrieve products from the 'second_db' database
$products = Product::all();