Laravel: connect to databases dynamically

前端 未结 4 1960
盖世英雄少女心
盖世英雄少女心 2020-11-29 03:52

I\'m creating an application in Laravel 5(.1) where it is needed to connect to different databases. The only problem is that it\'s not known which databases it has to connec

4条回答
  •  情书的邮戳
    2020-11-29 04:30

    You might need to use these:

    use Illuminate\Support\Facades\Config;
    use DB;
    

    Set database configurations:

            Config::set("database.connections.mysql_external", [
                'driver' => 'mysql',
                "host" => "localhost",
                "database" => "db_name",
                "username" => "root",
                "password" => "root",
                "port" => '8889',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
                'strict'    => false,
            ]);
    

    Connect to database and do stuff:

        $users = DB::connection('mysql_external')->select('Select id from users');
    

    Disconnect database and reset config variables

            DB::disconnect('mysql_external');
            Config::set("database.connections.mysql_external", [
                'driver' => 'mysql',
                "host" => "localhost",
                "database" => "",
                "username" => "",
                "password" => "",
                "port" => '',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
                'strict'    => false,
            ]);
    

提交回复
热议问题