0

I'm using Laravel 5.5 and MySQL, and I want to connect to multiple databases. I read many articles and most of them suggest to set config/database.php first, and in the controller use following code to connect to database:

$result = DB::connection('mysql2')->select($);

It works for me, but I have multiple databases and have saved the host & port in the main database.

is it possible to query the database list and connection information from the database itself and then put it into the config/database.php?

Or I should add the database list and connection information manually?

Sunny Sharma
  • 4,688
  • 5
  • 35
  • 73
Una
  • 41
  • 1
  • 1
  • 4

2 Answers2

0

I think you can refer to this How to make database query inside a config file? where u can query the database and put it in your config file.

kurapika
  • 166
  • 1
  • 12
0

I found a solution. Share it to everyone :)

First, make a Connection Model.

Then, add code in the app/Providers/AppServiceProvider.php

//connections
if (\Schema::hasTable('connections')) {
        $connections = \App\Models\Connection::all();
        $db = \Config::get('database.connections');
        foreach ($connections as $connection)
        {
            $db['cdb_'.$connection->id] = [
                    'driver'    => 'mysql',
                    'host'      => $connection->db_host,
                    'port'      => $connection->db_port,
                    'database'  => $connection->db_database,
                    'username'  => $connection->db_user,
                    'password'  => $connection->db_pass,
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci', //utf8_unicode_ci
                    'prefix'    => '',
                    'strict'    => false,
        ];
    }
    \Config::set('database.connections',$db);
}else{
    \Config::set('database.connections',[]);
}

Schema::defaultStringLength(191); 
Una
  • 41
  • 1
  • 1
  • 4