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.
Echo the Laravel database name in Blade/PHP The simplest way it to place the following script in a Blade or PHP file. This will output the name of the database or return 'none' if there is no connection. If you view it in the browser, it gives you the name of the connected database.
Laravel makes connecting with databases and running queries extremely simple. The database configuration file is app/config/database. php . In this file you may define all of your database connections, as well as specify which connection should be used by default.
In . env file you can set DB_CONNECTION with your database name and applicable databases are given in /config/database. php which are (SQLite, MySQL, pgSQL, SQLSRV) after that just type your username, password, and database name and you can use that database with port number.
Laravel makes interacting with databases extremely simple across a variety of supported databases using raw SQL, a fluent query builder, and the Eloquent ORM. Currently, Laravel provides first-party support for five databases: MariaDB 10.3+ (Version Policy) MySQL 5.7+ (Version Policy)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With