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.

推荐答案

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.

但是Laravel只会在需要数据库中的某个内容时连接到数据库,在try 连接时,如果发现任何错误,它将提高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.

在我看来,您不需要判断它是否连接,只需在异常处理闭包中采取适当的操作即可.

Laravel相关问答推荐

Laravel Horizo​​n 限制与优化

如何在 laravel 中为另一个用户 session()->forget('cart')?

为什么 laravel 模型会重复一组数据以及如何(如果可能)只有一组数据?

在 laravel 中动态更改时区

Laravel 附加额外字段

.gitignore 不忽略文件夹

通过单击按钮保存 PhpSpreadSheet

为什么我的 Laravel 队列作业(job)在 60 秒后失败?

file_put_content ...无法打开流:Laravel 5 中的权限被拒绝

laravel 预期响应代码 250 但得到代码530

Homebrew PHP 似乎没有链接

Cookie::forget 不工作 laravel 5.1

在共享主机中仅使用 FTP 部署 Laravel 5

如何在 laravel 中使用 GROUP_CONCAT

laravel 5.1 在没有 VM 重启的情况下看不到作业(job)文件的更改

Laravel 验证:数字和整数之间的区别?

Laravel 4 验证唯一(数据库)忽略当前

Laravel 删除集合中的第一项

Eloquent的 attach/detach/sync 触发任何事件?

你如何在 Laravel 5.3 的新通知服务生成的Electron邮件中添加图像?