且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Laravel 4中检查是否连接到数据库?

更新时间:2022-01-25 21:48:31

您可以使用

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.

但是... Laravel仅在需要数据库中的内容时才连接到数据库,并且在尝试连接时,如果发现任何错误,它将引发PDOException,因此您可以这样做将您的用户重定向到一个友好的页面:

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";
});

将此添加到您的app/filters.php文件中.

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.