How to check which database is connected in Laravel

Laravel is an amazing framework for rapid application creation. It allows you to easily connect to a database. However, for local deployment, there are chances that you need to confirm that your application is connected to a database. For example, during the debugging process, you often need to first check if you are connected to a database. Moreover, also read the name of the database you are connected to. Most importantly, when dealing with multiple databases at a time.

This tutorial will show you how to check which database a Laravel application is connected to.

simple code snippet as shown below detects the connection name for current database.

strong>Database Connected: </strong>
<?php
    try {
        \DB::connection()->getPDO();
        echo \DB::connection()->getDatabaseName();
        } catch (\Exception $e) {
        echo 'None';
    }
?>

We will enclose the code in a try-catch loop, as it gets the database via a PDO instance of a connection using the getPdo method.

If the database is present, the getDatabaseName() method will echo the database name, else it will echo ‘None’. In case if no database is present.

There are two ways you can add this code snipped to your Laravel application:

  1. Place it somewhere in a Blade template (Laravel View) or PHP-file (recommended for one-time debugging)
  2. Place it in a random file and dump() it to the dump-server (recommended for all other use cases).