Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 动态更改默认连接_Php_Mysql_Database_Laravel_Connection - Fatal编程技术网

Php 动态更改默认连接

Php 动态更改默认连接,php,mysql,database,laravel,connection,Php,Mysql,Database,Laravel,Connection,我在Laravel应用程序中有一个中间件,可以动态更改数据库连接: public function handle($request, Closure $next) { Config::set('database.default', 'mysql_'.$request->segment(1)); DB::reconnect('mysql_'.$request->segment(1)); app()->setLocale($request->segme

我在Laravel应用程序中有一个中间件,可以动态更改数据库连接:

public function handle($request, Closure $next)
{
    Config::set('database.default', 'mysql_'.$request->segment(1));
    DB::reconnect('mysql_'.$request->segment(1));
    app()->setLocale($request->segment(1));
    if (Auth::check() && session('locale') != $request->segment(1))
    {
        Auth::logout();
        return redirect('login');
    }
    return $next($request);
}
在这项工作中,默认连接将更改,但模型连接将保留旧的连接

在模型的转储中,我有:

“mysql_es”是由url段(/es)更改的默认连接

“mysql_it”是中间件更改之前的旧默认连接

谁能告诉我为什么


谢谢

您需要做的是清除连接

// Purge the current database connection, thus making Laravel get the default values all over again...
DB::purge('default');

// Now set the new connection
config(['database.default' => 'mysql_it']);

// ! Reconnect and close previous connection
DB::reconnect('default');

// Ping the database.
// This will throw an exception in case the database does not exists or the connection fails
Schema::connection('default')->getConnection()->reconnect();

我认为这是因为路由模型绑定在middlewareMaybe
dB::purge('mysql')之前使用默认的dB?我试过了,但没有成功。我解决了RouteServiceProvider中更改的db连接