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:
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:
'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.
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.
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)