To connect to multiple databases in Laravel, you can use the addConnection
method in the boot
method of your AppServiceProvider
.
Here’s an example:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
public function boot()
{
// Add a connection for the second database
$db2 = Config::get('database.connections.database2');
Config::set('database.connections.database2', array_merge(
$db2, ['prefix' => 'database2.']
));
DB::purge('database2');
DB::reconnect('database2');
}
- The
addConnection
method shown in the previous example can be added to theboot
method of theAppServiceProvider
class, which is located in theapp/Providers
directory. This method will be called every time the application boots, so you can use it to add additional database connections as needed. - In the
addConnection
method, we first retrieve the existing configuration for the second database from theconfig/database.php
file using theConfig::get
method. Then, we merge the existing configuration with a new prefix value using thearray_merge
function. This prefix will be added to all table names when using the second database connection. - After updating the configuration, we use the
DB::purge
andDB::reconnect
methods to reset the connection and reconnect to the second database using the updated configuration.
Then, in your config/database.php
file, you will need to add your second database connection as an element in the connections
array:
'database2' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
To use the second database in your code, you can use the DB::connection
method and pass in the name of the connection as a parameter:
$users = DB::connection('database2')->select('select * from users');
You can also set the default connection for a model by setting the $connection
property in the model class:
class User extends Model
{
protected $connection = 'database2';
}
With this setup, you can use the model’s ::all
method to retrieve all users from the second database:
$users = App\User::all();
- To use the second database in your code, you can use the
DB::connection
method and pass in the name of the connection as a parameter. This will return a newIlluminate\Database\Connection
instance configured for the specified connection. You can then use any of the available methods on this instance to query the database, such asselect
,insert
,update
, anddelete
. - You can also set the default connection for a model by setting the
$connection
property in the model class. This will cause all queries made through the model to use the specified connection by default. You can still use theDB::connection
method to override the default connection for a specific query if needed.
There are a few other ways you can connect to multiple databases in Laravel:
- You can create a separate database connection for each database you want to connect to, and then specify the connection name when performing queries. For example:
$users = DB::connection('database2')->select('select * from users');
$posts = DB::connection('database3')->select('select * from posts');
- You can create a custom database connection for each database you want to connect to, and then specify the connection name when performing queries. For example:
use Illuminate\Database\Connectors\ConnectionFactory;
use Illuminate\Database\Connection;
$factory = new ConnectionFactory(app());
$conn = $factory->make([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'root',
'password' => '',
]);
$conn->setName('database2');
$conn->setPdo($conn->getPdo());
$users = DB::connection('database2')->select('select * from users');
- You can create a custom database manager that manages multiple database connections and use it to perform queries. For example:
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Connectors\ConnectionFactory;
$factory = new ConnectionFactory(app());
$manager = new DatabaseManager(app(), $factory);
$manager->extend('database2', function () {
return [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'root',
'password' => '',
];
});
$users = $manager->connection('database2')->select('select * from users');
Each of these approaches has its own benefits and drawbacks, so you should choose the one that best fits your needs. I hope this helps! Let me know if you have any other questions.