How to check database connection in Laravel

In this example, we will check the database connection in Laravel. Before starting create a new Laravel application and start your database services like XAMPP or WAMPP and change database credentials in .env file.

Here, we will check database is connected and get an active database name using DB helper. For checking database exists or not in laravel then you can use DB PDO method.

Check Database Connection In Laravel

In this method, we will check whether our application is connected to the database or not. If connected then we will print name of the database.

Let's take an example to check Laravel application is connected or not:

<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TestController extends Controller
{
    public function checkConnection(){
        try {
            DB::connection()->getPDO();
            $database = DB::connection()->getDatabaseName();
            dd("Connected successfully to database ".$database.".");
        } catch (Exception $e) {
            dd("None");
        }
    }
}

In the above example, first of all, we have used the DB facade and getPDO() method which will check the database connection in the laravel application. If an application is connected to a database then it will print database name.

Get Connected Database Name In Laravel

Here, we will get the database name using DB helper. For that, we will use connection() method to get a current connection using the DB facade and getDatabaseName() method to get database name.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TestController extends Controller
{
    public function index(){
        if($dbName = DB::connection()->getDatabaseName())
        {
            dd("Connected successfully to database ".$dbName.".");
        }
    }
}

Conclusion

In this article, we have taken two examples to check database name or connections in Laravel. The first method will check the database connection from the PDO connection object while in the second method, we get the name of the database using any driver.