How to Check Database Connection in Laravel?

By Hardik Savani September 26, 2022 Category : Laravel

Hey Guys,

I am going to explain to you example of how to check database connection in laravel. let’s discuss about laravel check database connection. we will help you to give an example of laravel get database connection. Here you will learn laravel check if database is connected.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

If you need to check database connection exists or not in laravel. Then i will give you simple two examples using DB PDO and DB getDatabaseName().

So, let's see the below code:

Example 1:

app/Http/Controllers/DemoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

if(DB::connection()->getDatabaseName())

{

$database = DB::connection()->getDatabaseName();

dd("Connected successfully to database ".$database.".");

}

}

}

Output:

Connected successfully to database "my_database".

Example 2:

app/Http/Controllers/DemoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

use Exception;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

try {

DB::connection()->getPDO();

$database = DB::connection()->getDatabaseName();

dd("Connected successfully to database ".$database.".");

} catch (Exception $e) {

dd("None");

}

}

}

Output:

Connected successfully to database "my_database".

I hope it can help you...

Tags :