How to check if connected to database in Laravel 4

2019-03-11 06:02发布

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.

3条回答
手持菜刀,她持情操
2楼-- · 2019-03-11 06:21

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.

查看更多
唯我独甜
3楼-- · 2019-03-11 06:23

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";
});
查看更多
Emotional °昔
4楼-- · 2019-03-11 06:27

You can Use the following code :

try{
   DB::connection()->getDatabaseName();
}catch(Exception $e){
   echo $e->getMessage();
}
查看更多
登录 后发表回答