Laravel provides an easy database connection system. But sometimes we need to check laravel check if database connection exists or not. In this tutorial, I will show you how to check database connection in laravel 9. This example tutorial will give a complete concept of laravel 9 database connection check.

Using the DB::connection() helper, we can check whether db connection exists or not in Laravel. There are several ways to check laravel database connection. I will show you one of them. See the example code of laravel 9 check database connection:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;

class TutorialController extends Controller
{   
    public function index()
    {   
        try {
            $dbconnect = DB::connection()->getPDO();
            return "Connected successfully to the database";
        } catch(\Exception $e) {
            return "Error in connecting to the database";
        }
    }
}

 

If you run this above code, the output will be:

OUTPUT
Connected successfully to the database

 

Read also: How To Create And Use Blade Component In Laravel 9?

 

Conclusion

I have tried to discuss the clear concept of laravel 9 database connection check. Now we know laravel 9 check database connection. Hope this laravel check if database connection exists tutorial will help you.