How to check database connection in Laravel

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

Here, we will check database is connected and get an active database name using DB helper. To check database exists or not in Laravel then you can use the 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 the 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 the database name.

Get Connected Database Name In Laravel

Here, we will get the database name using DB helper. For that, we will use the connection() method to get a current connection using the DB facade and the getDatabaseName() method to get the 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 names 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.