Home » Php » php – How to use multiple connections one by module in Laravel

php – How to use multiple connections one by module in Laravel

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m creating an application in Laravel where each one will have its database, is it possible for each module to receive its connection file instead of leaving everything inside the config/database?

How to&Answers:

When you say module what do you mean by that?

Laravel supports multiple db connections, and in each Eloquent model you can add property $connection to specify which database connection to use for a specific model.

class MyClass extends Eloquent {

    protected $connection = 'myConnectionName';
    ...
}

make sure that all models that are in relations are within the same database though.
Add defintion of myConnectionName in config/database.php

Answer:

Yes its possible follow the following step and let me if any query

Step 1 : Add the second db code in config->database.php bottom of mysql=>[….]

'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST2', '100.10.0.100'),  // note add your hostname 
            'port' => env('DB_PORT2', '3306'),
            'database' => env('DB_DATABASE2', 'forge'),
            'username' => env('DB_USERNAME2', 'forge'),
            'password' => env('DB_PASSWORD2', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

Step 2 : Add the code in .evn file

DB_CONNECTION2=mysql
DB_HOST2=100.10.0.100 // Add your hostname
DB_PORT2=3306
DB_DATABASE2=test // add your DB name
DB_USERNAME2=testuser // add your user name
DB_PASSWORD2=test123 // add your pass

Step 3 : you can access in controller like (Note : use youe table name and fields)

$records= DB::connection('mysql2');       
       $records1 = $records->table('contact');
       $records2 = $records1->where('mobile',$client_mob)
                   ->where('delete',0)
                   ->first(['id','converted']);

All the best…