Laravel 使用用户输入的用户名和密码连接到数据库

Laravel connec to database with user inputed username and password

我正在尝试为我正在使用的 CMS 制作某种安装程序。 安装程序页面基本上是用户输入数据库主机、端口、用户名、密码和模式名称的页面。我如何使用此输入数据来测试我是否真的可以连接给定的输入?

您可以将用户输入输入控制器函数并更新 config/datadata.php。假设驱动默认是mysql,你可以这样做:

public function checkDatabaseConnection(Request $request)
{
    //update the config
     config(['database.connections.mysql' => [
        'host'     => $request->host,
        'username' => $request->username,
        'password' => $request->password
    ]]);

    //Check the credentials by calling PDO 
    try {
        DB::connection()->getPdo();
    } catch (\Exception $e) {
        return redirect()->back()->withErrors(["connection" => "Could not connect to the database.  Please check your input."]);
    }
}

不要忘记在控制器顶部添加 use DB