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 connects to the database. If it connects, we will print the database name.
Let’s take an example to see whether the Laravel application connects to the database 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, we first use the DB facade and the getPDO() method to check the database connection in the Laravel application. If the application connects to the database, it prints the database name.
Show Connected Database 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.
When working with Laravel, it’s often useful to see the actual SQL queries generated by Eloquent or the query builder. This can help debug issues, optimize performance, or simply understand how Laravel translates your code into SQL. For a deeper dive into inspecting and retrieving queries, check out our guide on Get SQL Query in Laravel, where we explore practical methods to capture and analyze SQL statements efficiently.

