Laravel 5.1 - Checking a Database Connection
PhpMysqlLaravelPhp Problem Overview
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.
- If database 1 is connected, save data to it
- If database 1 is not connected, check if database 2 is connected
- If database 2 is connected save data to it
- If database 2 is not connected, check if database 3 is connected
- 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?
Php Solutions
Solution 1 - Php
Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!
use Illuminate\Support\Facades\DB;
// Test database connection
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration. error:" . $e );
}
Solution 2 - Php
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.
Solution 3 - Php
You can use this, in a controller method or in an inline function of a route:
use Illuminate\Support\Facades\DB;
//....
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.");
}
Solution 4 - Php
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.
Solution 5 - Php
You can use this query for checking database connection in laravel:
use Illuminate\Support\Facades\DB;
// ...
$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 check out this page https://laravel.com/docs/5.0/database.
Solution 6 - Php
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.