How to use multiple database in Laravel 11

Using multiple databases in Laravel 11 allows you to distribute your data across different database connections, which can be helpful for various reasons like scalability, separation of concerns, or handling different types of data. Laravel provides built-in support for managing multiple database connections, and here’s how you can utilize it:

  1. Configure Database Connections: Start by configuring multiple database connections in your Laravel application. The database configuration file is located at config/database.php. Inside this file, you’ll find an array of database connections. You can define additional connections by adding entries to this array. Each connection should have a unique name and specify the database driver, host, database name, username, password, and any other required options.
'connections' => [
    'mysql' => [
        // Primary database connection configuration
    ],
    'mysql2' => [
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'database2',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
    ],
],

In this example, we’ve added a second MySQL database connection named mysql2.

  1. Define Models for Each Database: If you’re using Eloquent ORM, you’ll need to define models for each database connection. Each model should specify the connection it belongs to using the $connection property.
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Database2Model extends Model
{
    protected $connection = 'mysql2';
}

This ensures that queries made using this model are executed against the mysql2 database connection.

  1. Perform Database Operations: You can now perform database operations using the specified connections. When using Eloquent, you can specify the connection explicitly for each query or use the model’s default connection.
use App\Models\Database2Model;

// Specify connection explicitly
$users = Database2Model::on('mysql2')->where('active', true)->get();

// Use default connection defined in the model
$users = Database2Model::where('active', true)->get();
  1. Migrations and Seeders: When working with multiple databases, you’ll likely need to create migrations and seeders for each database separately. You can specify the connection for migrations using the --database option when running php artisan migrate command.
php artisan migrate --database=mysql2

Similarly, you can run seeders for specific databases using the --database option.

php artisan db:seed --database=mysql2

By following these steps, you can effectively use multiple databases in your Laravel 11 application, allowing you to manage and interact with different sets of data across various database connections.

Leave a Reply