DEV Community

Ankit Verma
Ankit Verma

Posted on

How to Use Multiple Databases in Laravel ?

Laravel support multiple databases within a single application. Whether you need to connect to different databases for various services or manage data across multiple environments, Laravel makes it easy to configure and query multiple connections seamlessly.

Configuring Multiple Databases

To configure multiple databases in Laravel, you need to update the config/database.php file. Laravel uses the connections array to define different database connections.

Step 1: Define Multiple Connections

Edit the config/database.php file and add your additional database connections under the connections array:

'second_db' => [
    'driver' => 'mysql',
    'host' => env('SECOND_DB_HOST', 'your_remote_host'),
    'database' => env('SECOND_DB_DATABASE', 'your_database'),
    'username' => env('SECOND_DB_USERNAME', 'your_username'),
    'password' => env('SECOND_DB_PASSWORD', 'your_password'),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],
Enter fullscreen mode Exit fullscreen mode

You can define as many connections as needed for your application.

Step 2: Set Up Environment Variables

To keep sensitive information secure, define the new database credentials in the .env file:

SECOND_DB_HOST=your_second_host
SECOND_DB_DATABASE=your_database
SECOND_DB_USERNAME=your_username
SECOND_DB_PASSWORD=your_password
Enter fullscreen mode Exit fullscreen mode

Using Multiple Database Connections

Once the connections are configured, you can start using them in your queries.

1. Querying Different Databases

Use the connection method to specify which database connection to use:

$users = DB::connection('second_db')->table('users')->get();
Enter fullscreen mode Exit fullscreen mode

2. Using Multiple Connections in Models

If you want a specific model to use a different database connection, set the $connection property in the model:

class RemoteUser extends Model
{
    protected $connection = 'second_db';
    protected $table = 'users';
}
Enter fullscreen mode Exit fullscreen mode

Now, you can use this model to interact with the SECOND_db database:

$users = RemoteUser::all();
Enter fullscreen mode Exit fullscreen mode

3. Running Migrations on a Specific Database

If you need to run migrations for a specific connection, use:

php artisan migrate --database=SECOND_db
Enter fullscreen mode Exit fullscreen mode

This ensures migrations are applied to the designated database connection.

Handling Transactions Across Databases

Laravel does not support cross-database transactions natively. However, you can handle multiple transactions using DB::transaction() individually:

DB::connection('mysql')->transaction(function () {
    DB::connection('second_db')->transaction(function () {
        // Perform database operations
    });
});
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay