Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if connected to database in Laravel 4?

Tags:

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.

like image 479
Andrew M Avatar asked Dec 11 '13 14:12

Andrew M


People also ask

How do I know if DB is Laravel connected?

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.

How does Laravel connect to 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.

How does Laravel connect to external database?

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.

What database does Laravel use?

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)


1 Answers

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.

like image 171
Antonio Carlos Ribeiro Avatar answered Sep 19 '22 11:09

Antonio Carlos Ribeiro