In this example, we will check the database connection in Laravel. Before starting create 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 active database name using DB helper. For checking database exists or not in laravel then you can use DB PDO method.
In this method, we will check our application is connected to 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.
Here, we will get database name using DB helper. For that, we will use connection() method to get current connection using 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.".");
}
}
}
In this article, we have taken two examples to check database name or connection 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.
Ask anything about this examples