Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

php - Laravel 5.1 - Checking a Database Connection

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, but this doesn't solve my problem.

I have three instances of MySQL that are set up on different machines. Below is a simplified version of what I am trying to achieve.

  1. If database 1 is connected, save data to it
  2. If database 1 is not connected, check if database 2 is connected
  3. If database 2 is connected save data to it
  4. If database 2 is not connected, check if database 3 is connected
  5. If database 3 is connected, save data to it

To be clear, is there a way to check that a database is connected in Laravel 5.1?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

use IlluminateSupportFacadesDB;

// Test database connection
try {
    DB::connection()->getPdo();
} catch (Exception $e) {
    die("Could not connect to the database.  Please check your configuration. error:" . $e );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...