To use multiple databases in Laravel, you can configure multiple database connections in your Laravel application's configuration file (`config/database.php`). Here's a step-by-step guide:
1. Open the `config/database.php` file in your Laravel project.
2. Inside the `connections` array, define your additional database connections. You can add an array for each database connection you want to use. For example, let's assume we want to add a second database connection named "secondary". Here's how it can be added:
```
'connections' => [
'mysql' => [
// Your default database connection configuration
],
'secondary' => [
'driver' => 'mysql',
'host' => env('DB_SECONDARY_HOST', 'localhost'),
'port' => env('DB_SECONDARY_PORT', '3306'),
'database' => env('DB_SECONDARY_DATABASE', 'secondary_db'),
'username' => env('DB_SECONDARY_USERNAME', 'root'),
'password' => env('DB_SECONDARY_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
// Other database connections...
],
```
Adjust the connection details such as `host`, `port`, `database`, `username`, and `password` to match your secondary database configuration. You can also provide these values in your `.env` file for easier management.
3. Next, define the corresponding environment variables in your `.env` file for the secondary database connection. Add the following lines to your `.env` file:
```
DB_SECONDARY_HOST=localhost
DB_SECONDARY_PORT=3306
DB_SECONDARY_DATABASE=secondary_db
DB_SECONDARY_USERNAME=root
DB_SECONDARY_PASSWORD=
```
Modify the values according to your secondary database configuration.
4. Now that you have defined the second database connection, you can use it in your Laravel application. To specify which database connection to use, you can set the `connection` property on your Eloquent models or specify the connection explicitly in your queries.
```
// Using the secondary database connection in a model
protected $connection = 'secondary';
```
```
// Using the secondary database connection in a query
$users = DB::connection('secondary')->table('users')->get();
```
By default, Laravel will use the connection defined in your `config/database.php` file for Eloquent models and queries if no explicit connection is specified.
With these steps, you can configure and use multiple databases in your Laravel application. You can define as many additional database connections as needed and use them by specifying the appropriate connection on your models or queries.
No comments:
Post a Comment