Home > Article > PHP Framework > Detailed explanation of how Laravel uses multiple databases (with code examples)
The following tutorial column of Laravel will introduce you to the method of using multiple databases in Laravel. I hope it will be helpful to you!
Use .env
>= 5.0 (Tested based on 5.5 Laravel 8 and also available)
In .env
File
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=database1DB_USERNAME=rootDB_PASSWORD=secretDB_CONNECTION_SECOND=mysqlDB_HOST_SECOND=127.0.0.1DB_PORT_SECOND=3306DB_DATABASE_SECOND=database2DB_USERNAME_SECOND=rootDB_PASSWORD_SECOND=secret
In config/database.php
File
'mysql' => [ 'driver' => env('DB_CONNECTION'), 'host' => env('DB_HOST'), 'port' => env('DB_PORT'), 'database' => env('DB_DATABASE'), 'username' => env('DB_USERNAME'), 'password' => env('DB_PASSWORD'),],'mysql2' => [ 'driver' => env('DB_CONNECTION_SECOND'), 'host' => env('DB_HOST_SECOND'), 'port' => env('DB_PORT_SECOND'), 'database' => env('DB_DATABASE_SECOND'), 'username' => env('DB_USERNAME_SECOND'), 'password' => env('DB_PASSWORD_SECOND'),],
Note: In
mysql2
, ifdb_username
anddb_password
are the same, then you can useenv('DB_USERNAME')
.
Mode
To specify which connection to use, just use the connection()
method
Schema::connection('mysql2')->create('some_table', function($table){ $table->increments('id'):});
Query Producer
$users = DB::connection('mysql2')->select(...);
Model
Set the $connection
variable in the model.
class SomeModel extends Eloquent { protected $connection = 'mysql2';}
You can also define the connection at runtime through the setConnection
method or the on
static method:
class SomeController extends BaseController { public function someMethod() { $someModel = new SomeModel; $someModel->setConnection('mysql2'); // non-static method $something = $someModel->find(1); $something = SomeModel::on('mysql2')->find(1); // static method return $something; }}
Note Be careful when trying to establish relationships with tables that span databases! This can be used, but it may come with some caveats and depends on the database and database setup you have.
Using multiple database connections
When using multiple connections , you can access each connection through the connection method on the DB
facade class. The name passed to the connection
method should correspond to a connection listed in the config/database.php
configuration file:
$users = DB::connection('foo')->select(...);
You can also access the original underlying PDO instance using the getPdo
method on the connection instance:
$pdo = DB::connection()->getPdo();
Original address: https://stackoverflow.com/questions/ 31847054/how-to-use-multiple-databases-in-laravel
Translation address: https://learnku.com/laravel/t/62110
The above is the detailed content of Detailed explanation of how Laravel uses multiple databases (with code examples). For more information, please follow other related articles on the PHP Chinese website!