Sometimes we need to get the database connection name in laravel. Assume there is multiple database connection name in your laravel application. Now you need to get the laravel get current database connection name. So in this tutorial, I will help you that how to get the current database connection name in Laravel.

Using the getDatabaseName() helper method, we can get the current database connection name in laravel. See the example code from below:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;

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

 

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

OUTPUT
Connected database name is: test

 

Read also: How To Check Database Connection In Laravel 9?

 

Conclusion

I have tried to discuss the clear concept of laravel get current database connection name. Now we know laravel get database connection name. Hope this laravel get current database connection name tutorial will help you.