How to Check Database Connection in Laravel 2022?

Hello dev, Today we are going to learn How to Check Database Connection in Laravel? This tutorial will cover on how you can check database connection in laravel application.

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:

Also Read: How to Convert Image to Base64 in Laravel?

Examples on How to Check Database Connection in Laravel

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".

Also Read: How to Truncate String in Laravel?

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".

Also Read: How to Get All Routes in Laravel 9 ? [ New / Free Tutorials ]

Conclusion

Today, We had learn How to Check Database Connection in Laravel?. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Related Question also Ask

  • How do I know if a database is connected in Laravel?
  • How does Laravel connect to external database?
  • In which file we need to set the database connection in Laravel?
  • Can Laravel connect to SQL Server?

Also Read: How to Get All Files in a Directory in Laravel (2022)

3 Comments

Leave a Reply