How to Check Database Connection in Laravel?
Hey Guys,
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, laravel 9, laravel 10 and laravel 11 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:
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".
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".
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel - How to Get All Files in a Directory?
- How to Get All Routes in Laravel?
- Laravel Download File from URL to Storage Example
- How to Write Text on Existing PDF File in Laravel?
- How to Get Browser Name and Version in Laravel?
- How to Convert JSON to Array in Laravel?
- Laravel Cashier Stripe Subscription Example Tutorial
- How to Use Enum in Laravel?
- How to use Try Catch Exception in Laravel App?
- How to Add Two Factor Authentication with SMS in Laravel?
- Laravel Livewire Datatables Example Tutorial
- How to use DB Transactions in Laravel?