Published in


How to use multiple database in Laravel

Jan 01, 2021, Originally published at ・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


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 [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', ''),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST_SECOND', ''),
'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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Smit Pipaliya

Smit Pipaliya

I am Senior Developer at ServerAvatar Technology.