How to Use Multiple Databases in Laravel: A Step-by-Step Guide

If you’re developing a Laravel application that needs to access data from multiple databases, you might be wondering how to configure and use multiple database connections in your Laravel application. In this article, we’ll guide you through the process of configuring and using multiple database connections in Laravel with an example.

Understanding Laravel Database Configuration

Before we get started with configuring and using multiple databases in Laravel, let’s take a moment to understand Laravel’s default database configuration. By default, Laravel uses the config/database.php file to define the database connection settings.

In this file, you can define multiple database connections with different names, and then specify which connection to use for each model in your application. Laravel supports several database drivers, including MySQL, PostgreSQL, SQLite, and SQL Server.

Configuring Multiple Databases in Laravel

To configure multiple databases in Laravel, we need to define the database connections in the config/database.php file. Let’s create two databases, database1 and database2, and configure them in the config/database.php file.

'connections' => [

    'database1' => [
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'database1',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
    ],

    'database2' => [
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'database2',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
    ],

],

In the above code, we defined two database connections, database1 and database2, with their respective settings. We can now use these connections in our Laravel application.

Using Multiple Databases in Laravel

To use a specific database connection for a model in Laravel, we need to define the $connection property in the model class. Let’s say we have a User model, and we want to use the database2 connection for this model. Here’s how we can define the $connection property in the User model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $connection = 'database2';

    // ...
}

In the above code, we defined the $connection property in the User model and set it to database2. Now, any query on the User model will use the database2 connection instead of the default connection.

If we want to use a different connection for a specific query instead of defining the $connection property in the model, we can use the on method of the query builder. Here’s an example:

$users = DB::connection('database1')->table('users')->get();

In the above code, we’re using the connection method of the DB facade to switch to the database1 connection, and then we’re using the table method to specify the users table and the get method to retrieve the data.

Example: Using Multiple Databases in a Laravel Application

Let’s take an example of a Laravel application that needs to access data from multiple databases. We have two databases, database1 and database2, with a users

table in each database. We want to retrieve the users from both databases and display them on a single page. Here’s how we can achieve this:

First, we need to define the database connections in the config/database.php file as we did earlier. Once we have defined the connections, we can create two models, Database1User and Database2User, for the users table in each database.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Database1User extends Model
{
    protected $table = 'users';
    protected $connection = 'database1';
}

class Database2User extends Model
{
    protected $table = 'users';
    protected $connection = 'database2';
}

In the above code, we defined two models, Database1User and Database2User, with their respective $table and $connection properties set.

Now, in our controller, we can retrieve the users from both databases and pass them to the view as follows:

<?php

namespace App\Http\Controllers;

use App\Models\Database1User;
use App\Models\Database2User;

class UserController extends Controller
{
    public function index()
    {
        $users1 = Database1User::all();
        $users2 = Database2User::all();

        return view('users.index', compact('users1', 'users2'));
    }
}

In the above code, we’re retrieving all the users from Database1User and Database2User models and passing them to the users.index view.

Finally, in our view, we can display the users from both databases as follows:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($users1 as $user)
            <tr>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
        @endforeach
        @foreach ($users2 as $user)
            <tr>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

In the above code, we’re using the @foreach loop to iterate over the users from both databases and display their name and email in a table.

Conclusion

In this article, we learned how to configure and use multiple databases in a Laravel application. We defined two database connections in the config/database.php file and used them to create two models for the users table in each database. We then retrieved the users from both databases in our controller and displayed them on a single page in our view.

Using multiple databases in Laravel can be useful in scenarios where you need to access data from multiple databases or work with legacy databases. With Laravel’s built-in support for multiple database connections, it’s easy to configure and use multiple databases in your application.

FAQs

Can I use more than two databases in Laravel?

Yes, you can define as many database connections as you want in the config/database.php file.

Can I use different database drivers for each connection in Laravel?

Yes, Laravel supports multiple database drivers, and you can specify a different driver for each connection.

How do I switch between multiple database connections in Laravel?

You can define the $connection property in your model or use the connection method of the DB facade to switch between multiple database connections.

Can I use multiple databases in the same query in Laravel?

Yes, you can use the join method of the DB facade to join tables from different databases in the same query.

Can I use multiple databases with different versions of MySQL in Laravel?

Yes, Laravel supports multiple database drivers, and you can specify a different driver for each connection. So, you can use different versions of MySQL or even different databases like PostgreSQL or SQL Server.

I hope this article has been helpful in understanding how to use multiple databases in Laravel. With the steps outlined in this article, you can easily configure and use multiple databases in your Laravel application. If you have any further questions or feedback, please feel free to leave a comment below.

Test Your Knowledge of Laravel ORM

A Quiz on Object-Relational Mapping with Laravel

Leave a comment

0.0/5