How to make a multi database connection in laravel ? #5
-
Can Anyone tell me about laravel multi database connection usecase? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Configure Database Connections in config/database.php: 'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
// ...
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_PG_HOST', '127.0.0.1'),
'database' => env('DB_PG_DATABASE', 'forge'),
'username' => env('DB_PG_USERNAME', 'forge'),
'password' => env('DB_PG_PASSWORD', ''),
// ...
],
// ...
], Set Environment Variables: DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=my_mysql_db
DB_USERNAME=root
DB_PASSWORD=
DB_PG_CONNECTION=pgsql
DB_PG_HOST=127.0.0.1
DB_PG_DATABASE=my_pgsql_db
DB_PG_USERNAME=postgres
DB_PG_PASSWORD=password Using Multiple Database Connections: // Using the "mysql" connection
$users = DB::connection('mysql')->table('users')->get();
// Using the "pgsql" connection
$products = DB::connection('pgsql')->table('products')->get();
Eloquent Models with Different Connections:
If you have Eloquent models associated with different databases, you can define the connection in the model:
class User extends Model {
protected $connection = 'mysql';
// ...
}
class Product extends Model {
protected $connection = 'pgsql';
// ...
} Now, you have set up multiple database connections in Laravel. You can interact with these databases as needed based on the connections you've defined. |
Beta Was this translation helpful? Give feedback.
Configure Database Connections in config/database.php:
Open the config/database.php file and define your database connections in the connections array. You can name your connections whatever you like. For example, let's create two connections named "mysql" and "pgsql":