How to use multiple database in Laravel

Smit Pipaliya
TechvBlogs
Published in
2 min readJan 30, 2022

Jan 01, 2021, Originally published at techvblogs.com ・2 min read

Laravel is a free, open-source PHP framework, created by Taylor Otwell . It follows a Model-View-Controller (MVC) design pattern. Laravel reuses the existing components of different frameworks which helps to create a perfect and outstanding web application. If you are familiar with PHP, Advance PHP it will make your task easier. Laravel is secure and prevents web attacks using their CSRF (Cross-site Request Forgery) protection.

While developing a web application some times we need to use multiple databases because of project requirement or large scale projects, in this time laravel allows to use multiple database connections. You can easily learn how to use multiple databases with laravel in this blog.

Add Database Connection Detail in .env

DB_HOST_SECOND="DB HOST HERE"
DB_PORT_SECOND="DB PORT HERE"
DB_DATABASE_SECOND="DATABASE NAME HERE"
DB_USERNAME_SECOND="DB USERNAME HERE"
DB_PASSWORD_SECOND="DB PASSWORD HERE"

As you can see, you can go with multiple if you want to use more databases, also you can go with other database engines. Here we use MySQL.

Configure database detail in config / database.php

add detail in the connections array.

<?phpreturn [
'connections'=>[
'mysql'=>[
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
],
'mysql_second'=>[
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST_SECOND', '127.0.0.1'),
'port' => env('DB_PORT_SECOND', '3306'),
'database' => env('DB_DATABASE_SECOND', 'forge'),
'username' => env('DB_USERNAME_SECOND', 'forge'),
'password' => env('DB_PASSWORD_SECOND', ''),
]
]
];
?>

Note: Add All Detail Of Database Connection Here we add only database detail for learning purposes.

Now We learn How to use this connection with Schema , Query , and Eloquent Model .

Schema Builder

With Schema Builder, You can use any connection by simply run the connection()method:

Schema::connection('mysql_second')->create('table_name', function($table){
// entire code here
});

Query Builder

Similar to Schema Builder, you can define a connection in Query Builder:

$posts = \DB::connection('mysql_second')->select('id','title')->get();

Eloquent Model

Similar to Query Builder, you can define a connection in the Eloquent Model:

<?phpnamespace App\Models;class Post extends Eloquent {
protected $connection = 'mysql_second';
}
?>

Also, you can use the connection in custom join queries. with this simple example:

\DB::table('posts')->join('mysql_second.types as secondDbType','posts.code','=','secondDbType.code')->first();

Thank you for reading this blog.

--

--

Smit Pipaliya
TechvBlogs

I am Project Manager at ServerAvatar Cloud Technology.