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?

2
  • 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, 2015 at 9:38
  • @milz That was my first thought, but I was hoping for a pre-existing method for this.
    – Enijar
    Oct 30, 2015 at 9:41

7 Answers 7

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 );
}
7
  • 1
    @YasserMoussa, you put it wherever you need to check for a working connection to the DB.
    – alexw
    Jun 10, 2017 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 ? Jun 10, 2017 at 21:31
  • 1
    Not sure - maybe try #laravel in Freenode IRC for help with your specific situation.
    – alexw
    Jun 10, 2017 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. Jul 6, 2017 at 13:50
  • 1
    guys, you can create a route and add these code to test :D May 4, 2018 at 2:07
117

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.

3
  • Can you provide a link to the original solution? Jan 2, 2018 at 14:18
  • 4
    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. Jan 24, 2019 at 9:04
  • This is actually faster than write down a function Sep 22, 2020 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.");
    }
2
  • 1
    you can add this as inline function in routes (web.php) or in any controller method
    – Luca C.
    Sep 3, 2017 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). Mar 2, 2020 at 16:41
19

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.

1
  • Beware this requires the DB user in the app to have access to the db information_schema to be successful Oct 8 at 5:38
10

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.

5
  • 16
    This check appears to read from the configuration, not the active connection. This still reports connected succesfully if connection params are incorrect. Nov 2, 2016 at 6:05
  • 3
    This code just returns values in configuration file! Dec 25, 2016 at 12:45
  • 9
    This answer is misleading. Anyone coming here must look at @alexw's answer below Feb 15, 2017 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, 2021 at 8: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, 2021 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

1
  • in laravel 9 you can do php artisan db:show Dec 2, 2022 at 15:41
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.

2
  • 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 7, 2015 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, 2016 at 4:39

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.