How can I check if laravel is connected to the database? I\'ve searched around and I can\'t find anything that would tell me how this is done.
working :) -
Just added this code to app/filters.php
App::error(function(PDOException $exception)
{
Log::error("Error connecting to database: ".$exception->getMessage());
return "Error connecting to database";
});
You can Use the following code :
try{
DB::connection()->getDatabaseName();
}catch(Exception $e){
echo $e->getMessage();
}
You can use
if(DB::connection()->getDatabaseName())
{
echo "Connected sucessfully to database ".DB::connection()->getDatabaseName().".";
}
It will give you the database name for the connected database, so you can use it to check if your app is connected to it.
But... Laravel will only connect to database once it needs something from database and, at the time of a connection try, if it finds any errors it will raise a PDOException
, so this is what you can do to redirect your user to a friendly page:
App::error(function(PDOException $exception)
{
Log::error("Error connecting to database: ".$exception->getMessage());
return "Error connecting to database";
});
Add this to your app/filters.php
file.
In my opinion, you don't really need to check if it is connceted or not, just take the proper action in the exception handling closure.