如何检查是否已连接到 Laravel 4 中的数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20521737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if connected to database in Laravel 4?
提问by Andrew M
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.
如何检查laravel是否连接到数据库?我四处搜索,但找不到任何可以告诉我这是如何完成的。
回答by Antonio Carlos Ribeiro
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:
但是... Laravel 只会在需要数据库中的某些内容时才连接到数据库,并且在尝试连接时,如果发现任何错误,它将引发PDOException
,因此您可以这样做将用户重定向到友好的页:
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.
将此添加到您的app/filters.php
文件中。
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.
在我看来,您真的不需要检查它是否已连接,只需在异常处理闭包中采取适当的措施即可。
回答by ahm_selim
You can Use the following code :
您可以使用以下代码:
try{
DB::connection()->getDatabaseName();
}catch(Exception $e){
echo $e->getMessage();
}
回答by broadcastip
working :) -
在职的 :) -
Just added this code to app/filters.php
刚刚将此代码添加到 app/filters.php
App::error(function(PDOException $exception)
{
Log::error("Error connecting to database: ".$exception->getMessage());
return "Error connecting to database";
});