How to Check Database Connection in 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 AppHttpControllers;

use IlluminateHttpRequest;

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:.medrectangle-4-multi-155{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:0!important;margin-right:0!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

app/Http/Controllers/DemoController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

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…

1 thought on “How to Check Database Connection in Laravel?”

Leave a Comment