Laravel Connect Multiple Databases in Same Project
We can easily connect to multiple databases in the same project. Let’s follow these simple steps:
Table of Contents
Step 1 : Update .env File
Open .env file from your project. Make some env variables for new database. Have a look at the example:
.env
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=pass
DB_HOST_SECOND=localhost
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=pass
Step 2 : Configure database.php
Now we have to configure the database.php. Open database .php from config/database.php
and duplicate the present mysql array & renamed to mysql_second. See this example:
database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
------------
],
'mysql_second' => [
'driver' => 'mysql',
'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'),
------------
],
Step 3 : Connect to New Database
We have completed all configuration tasks. Let’s connect to new database.
TestDBController.php
class TestDBController extends Controller
{
public function index()
{
$db_ext = \DB::connection('mysql_second');
$users= $db_ext->table('users')->get();
print_r($users);
}
}
We are done. I hope this article will help you.Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.