Check If Database Connection is Successful in Laravel

Hey Artisan,

I am going to show to you an example of how to check database connection in laravel. let’s discuss laravel check database connection tutorial. I will help you to give an example of laravel get database connection in laravel 9. Here you will learn from this example tutorial is laravel check if database is connected.

You can use this source code with laravel 6, laravel 7, laravel 8 and laravel 9 versions. Sometimes we need to check db connection in laravel and If you need to check database connection exists or not in laravel then this example is for you. I will give you simple two examples using DB PDO and DB getDatabaseName().

So, let's see the below code:


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StudentController extends Controller{
   public function index() {
      try {
         $dbconnect = DB::connection()->getPDO();
         $dbname = DB::connection()->getDatabaseName();
         echo "Connected successfully to the database. Database name is :".$dbname;
      } catch(Exception $e) {
         echo "Error in connecting to the database";



The output of the above code is −

Connected successfully to the database. Database name is :test


Example 2

public function boot(){
   try {
      dump('Database is connected. Database Name is : ' . DB::connection()->getDatabaseName());
   } catch (Exception $e) {
      dump('Database connection failed');


Read also: Laravel Eloquent Find by Column Query Example


Hope it can help you.


Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js