Laravel Database Connection Check with Example

In this tutorial, we will learn how to check your Laravel database connection. We will give you simple two examples using DB PDO and DB getDatabaseName().

A line of code will return "none" if the name of the current database connection cannot be identified. There are two methods.

  • Anywhere in a Blade template or PHP file will do.
  • Place it in a random file and dump() it to the dump server

1. Echo the Laravel database name in Blade/PHP

The following script should be added to a Blade or PHP file for the simplest solution. If there is no connection, this will return "none" or the name of the database.

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

2. Using the dump server to check this

However, you could also put it in a controller or the boot() function in the app/Providers/AppServiceProvider.php file, in addition to Blade or PHP. Personally, I think it ought to go in the boot() procedure.

try {
    \DB::connection()->getPDO();
    dump('Database connected: ' . \DB::connection()->getDatabaseName());
} catch (\Exception $e) {
    dump('Database connected: ' . 'None');
}

Using the php artisan dump-server command to check the database connection.

#laravel #php 

Laravel Database Connection Check with Example
1.95 GEEK