Laravel 5.1 - Checking a Database Connection

前端 未结 6 1518
粉色の甜心
粉色の甜心 2020-12-13 02:10

I am trying to check if a database is connected in Laravel.

I\'ve looked around the documentation and can\'t find anything. The closest thing I\'ve found is this, bu

相关标签:
6条回答
  • 2020-12-13 02:10

    You can also run this:

    php artisan migrate:status
    

    It makes a db connection connection to get migrations from migrations table. It'll throw an exception if the connection fails.

    0 讨论(0)
  • 2020-12-13 02:19

    You can use this, in a controller method or in an inline function of a route:

       try {
            DB::connection()->getPdo();
            if(DB::connection()->getDatabaseName()){
                echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
            }else{
                die("Could not find the database. Please check your configuration.");
            }
        } catch (\Exception $e) {
            die("Could not open connection to database server.  Please check your configuration.");
        }
    
    0 讨论(0)
  • 2020-12-13 02:22

    Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!

    // Test database connection
    try {
        DB::connection()->getPdo();
    } catch (\Exception $e) {
        die("Could not connect to the database.  Please check your configuration. error:" . $e );
    }
    
    0 讨论(0)
  • 2020-12-13 02:28

    Another Approach:

    When Laravel tries to connect to database, if the connection fails or if it finds any errors it will return a PDOException error. We can catch this error and redirect the action

    Add the following code in the app/filtes.php file.

    App::error(function(PDOException $exception)
    {
        Log::error("Error connecting to database: ".$exception->getMessage());
    
        return "Error connecting to database";
    });
    

    Hope this is helpful.

    0 讨论(0)
  • 2020-12-13 02:29

    You can use alexw's solution with the Artisan. Run following commands in the command line.

    php artisan tinker
    DB::connection()->getPdo();
    

    If connection is OK, you should see

    CONNECTION_STATUS: "Connection OK; waiting to send.",

    near the end of the response.

    0 讨论(0)
  • 2020-12-13 02:37

    You can use this query for checking database connection in laravel:

    $pdo = DB::connection()->getPdo();
    
    if($pdo)
       {
         echo "Connected successfully to database ".DB::connection()->getDatabaseName();
       } else {
         echo "You are not connected to database";
       }
    

    For more information you can checkout this page https://laravel.com/docs/5.0/database.

    0 讨论(0)
提交回复
热议问题