diff --git a/src/Controllers/EnvironmentController.php b/src/Controllers/EnvironmentController.php index 8b678ab..28e02a8 100755 --- a/src/Controllers/EnvironmentController.php +++ b/src/Controllers/EnvironmentController.php @@ -2,9 +2,11 @@ namespace RachidLaasri\LaravelInstaller\Controllers; +use Exception; use Illuminate\Routing\Controller; use Illuminate\Http\Request; use Illuminate\Routing\Redirector; +use Illuminate\Support\Facades\DB; use RachidLaasri\LaravelInstaller\Helpers\EnvironmentManager; use RachidLaasri\LaravelInstaller\Events\EnvironmentSaved; use Validator; @@ -92,8 +94,13 @@ public function saveWizard(Request $request, Redirector $redirect) $validator = Validator::make($request->all(), $rules, $messages); if ($validator->fails()) { - $errors = $validator->errors(); - return view('vendor.installer.environment-wizard', compact('errors', 'envConfig')); + return $redirect->route('LaravelInstaller::environmentWizard')->withInput()->withErrors($validator->errors()); + } + + if (!$this->checkDatabaseConnection($request)) { + return $redirect->route('LaravelInstaller::environmentWizard')->withInput()->withErrors([ + 'database_connection' => 'Could not connect to the database.', + ]); } $results = $this->EnvironmentManager->saveFileWizard($request); @@ -103,4 +110,41 @@ public function saveWizard(Request $request, Redirector $redirect) return $redirect->route('LaravelInstaller::database') ->with(['results' => $results]); } + + + /** + * Validate database connection with user credentials (Form Wizard). + * + * @param Request $request + * @return boolean + */ + private function checkDatabaseConnection(Request $request) + { + $connection = $request->input('database_connection'); + + $settings = config("database.connections.$connection"); + + config([ + 'database' => [ + 'default' => $connection, + 'connections' => [ + $connection => array_merge($settings, [ + 'driver' => $connection, + 'host' => $request->input('database_hostname'), + 'port' => $request->input('database_port'), + 'database' => $request->input('database_name'), + 'username' => $request->input('database_username'), + 'password' => $request->input('database_password'), + ]), + ], + ], + ]); + + try { + DB::connection()->getPdo(); + return true; + } catch (Exception $e) { + return false; + } + } }