How To Check Database Connection In Laravel 9?

Hello artisan,

In this tutorial, I will show you how to check database connection in laravel 9 application. I will show you to give an example of laravel get database connection. Here you will learn laravel check if database is connected or not in Laravel.

If you need to check database connection exists or not in Laravel then we can check the database connection using DB PDO and DB getDatabaseName(). Let's see the example code of check database connection in Laravel:

app/Http/Controllers/DemoController.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.".");
        }
  
    }
}

 

You can check another way like:

app/Http/Controllers/DemoController.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");
        }
    
    }
}

 

Read also: Laravel 9 Gates and Policies Tutorial with Example

 

Hope it can help you.

 

#laravel #laravel-9x