How to use multiple databases in Laravel?

Web Development

I want to combine multiple databases in my system. Most of the time the database is MySQL; but it may differ in future i.e. Admin can generate such a reports which is use source of heterogeneous database system.

Does Laravel provide any Facade to deal with such situations? Or any other framework have more suitable capabilities for problem is?


If you want to unleash your potential in this competitive field, please visit the Web Development course page for more information, where you can find the Web Development tutorials and Web Development frequently asked interview questions and answers as well.

1
Answers

Replies

Ans: Laravel is flexible to provide its inbuilt support for the multiple databases. All you need to do is provide the connection details in config/database.php file.


return [

    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [

        'mysql' => [

            'driver' => 'mysql',

            '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', ''),

            'charset' => 'utf8',

            'collation' => 'utf8_unicode_ci',

            'prefix' => '',

            'strict' => false,

            'engine' => null,

        ],

'mysqlOne' => [

            'driver' => 'mysql',

            'host' => env('DB_HOST_ONE', '127.0.0.1'),

            'port' => env('DB_PORT', '3306'),

            'database' => env('DB_DATABASE_ONE', 'forge'),

            'username' => env('DB_USERNAME_ONE', 'forge'),

            'password' => env('DB_PASSWORD_ONE', ''),

            'charset' => 'utf8',

            'collation' => 'utf8_unicode_ci',

            'prefix' => '',

            'strict' => false,

            'engine' => null,

        ],

];


Once this is done, you are allowed to create two base model class for each connection  and define the connection name in each of these models.


//BaseModel.php


protected $connection = 'mysql';


//BaseModelOne.php


protected $connection = 'mysqlOne';


You are also allowed to extend these models where you can create more models for tables in each DB.

 
 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
To Top