74

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?

Enijar
  • 6,387
  • 9
  • 44
  • 73
  • The most obvious way would be to select something from the database within a try - catch. Whenever an exception is throwed the server / connection is not available (assuming there aren't any other errors - you might want to use the exception code here, to assure it's not a query problem (like missing a column or something)). – Luís Cruz Oct 30 '15 at 09:38
  • @milz That was my first thought, but I was hoping for a pre-existing method for this. – Enijar Oct 30 '15 at 09:41

7 Answers7

156

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 );
}
Player1
  • 2,878
  • 2
  • 26
  • 38
alexw
  • 8,468
  • 6
  • 54
  • 86
  • 1
    @YasserMoussa, you put it wherever you need to check for a working connection to the DB. – alexw Jun 10 '17 at 16:46
  • 2
    @alexw ok for example i need to use this code when laravel on first time boot so i used it in AppServiceProvider on boot() method and on catch die() worked but return view('errors.database') which i need didn't work it just showed laravel errors page .. am i missing something ? – Yasser Moussa Jun 10 '17 at 21:31
  • 1
    Not sure - maybe try #laravel in Freenode IRC for help with your specific situation. – alexw Jun 10 '17 at 22:12
  • 1
    This won't work for me - getPdo() timeout is longer than nginx timeout and I don't want to mess with server configuration, I just want to check if I can access my database. – Serge Kuharev Jul 06 '17 at 13:50
  • 1
    guys, you can create a route and add these code to test :D – Manh Nguyen May 04 '18 at 02:07
  • 1
    I would recommend doing: die($e) for this gives the error message too, it's more clear than just a homemade message +1 though for finding this – Mister Verleg Jun 22 '18 at 08:52
  • 1
    How do we call this code every time not violating SOLID principles? This does not address this scenario. – kta Apr 28 '19 at 08:30
115

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.

Luboš Miřatský
  • 1,459
  • 1
  • 12
  • 15
  • Can you provide a link to the original solution? – lofihelsinki Jan 02 '18 at 14:18
  • 3
    BTW, `php artisan tinker` `DB:connection()` can target any API public endpoint from `vendor/laravel/framework/src/Illuminate/Database/Connection.php` class, in particular, `getConfig()`, which is really convenient to get the information details to connect to the DB in presence, allowing you to try that connection manually from the client of your choice. – Fabien Haddadi Jan 24 '19 at 09:04
  • This is actually faster than write down a function – Andres Felipe Sep 22 '20 at 22:41
20

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.");
    }
Pathros
  • 10,042
  • 20
  • 90
  • 156
Luca C.
  • 11,714
  • 1
  • 86
  • 77
  • 1
    you can add this as inline function in routes (web.php) or in any controller method – Luca C. Sep 03 '17 at 13:16
  • 1
    As far as I've tested, it seems like the `->getDatabaseName()` part is not needed, since `->getPdo()` will already thrown an error (if I'm wrong I'll be happy to know that). – giovannipds Mar 02 '20 at 16:41
18

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.

Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
9

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.

Pathros
  • 10,042
  • 20
  • 90
  • 156
Dawlatzai Ghousi
  • 3,780
  • 2
  • 20
  • 26
  • 16
    This check appears to read from the configuration, not the active connection. This still reports connected succesfully if connection params are incorrect. – scottlimmer Nov 02 '16 at 06:05
  • 3
    This code just returns values in configuration file! – Hamid Parchami Dec 25 '16 at 12:45
  • 9
    **This answer is misleading. Anyone coming here must look at @alexw's answer below** – Peter Chaula Feb 15 '17 at 15:54
  • 1
    For later readers confused by the comments about this being a wrong answer when it seems to be basically the same as @alexw's, the reason is: this answer,used to read `if(DB::connection()->getDatabaseName())`, but after the comment feedback, the answer was updated to use `DB::connection()->getPdo()` instead – Daryn Jan 21 '21 at 08:51
  • For later readers confused by the top two comments about returning configuration and not doing any checks, they are erroneous. Make sure you test by not changing the last digit in the localhost IP address (like. 127.0.0.1 to 127.0.0.23) as the 2nd address will still resolve to your localhost thus making this check useless. – Alex May 21 '21 at 15:29
2

I don't know if this worked in that version of laravel, but at least on newer ones you can run

php artisan db 

and if your app can access the database then you should see a cli repl for it, for postgres you will see a psql instance

super potion
  • 105
  • 9
0

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.

ArtisanBay
  • 1,001
  • 11
  • 16
  • Did you mean app/filters.php ? Missing an 'r' there. The question is laravel 5.1 and laravel structure in 5.1 doesn't use app/filters.php directory. That is for laravel 4. – MaXi32 Dec 07 '15 at 22:41
  • From redbear's comment: @ArtisanBay's approach sounds like a working one. If filter is no longer available, perhaps you may try to write in a middleware. – justAbit Jul 27 '16 at 04:39