Check if Credentials for Database are valid with Laravel

I’m writing a small tool for which it is necessery to check if database-credentials are valid and working. The tool is based on laravel. The credentials are submitted via a post-route.

    $mysql2 = array(
        'driver'    => 'mysql',
        'host'      => 'localhosts',
        'database'  => 'test',
        'username'  => 'testUser',
        'password'  => 'testPasswort',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',


I hoped I could do something like this code above. But I can’t get it working. Has anyone ever attempted something similar?


I tried switching the credentials in the config file:

Config::set("database.connections.mysql", [
        "host" => "localhast",
        "database" => "test",
        "username" => "testUser",
        "password" => "testPasswort"
$con = DB::connection()->getPdo();

Sadly there is still some error thrown.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Have you tried using a new connection (not editing the already existing one)

$newName = uniqid('db'); //example of unique name

Config::set("database.connections.".$newName, [
        "host" => "localhast",
        "database" => "test",
        "username" => "testUser",
        "password" => "testPasswort"
try {
} catch (Exception $e) {
    //handle error

Method 2

You don’t need to pass the array to check DB connection just simply apply this code you will get to know about connection. This will automatically take the .env file connection variables.

try {
} catch (Exception $e) {
    die("Could not connect to the database.  Please check your configuration. error:" . $e );

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x