How to check if connected to database in Laravel 4?

laravel, laravel-4

Solution

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.

Problem

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.

Original source