Laravel check database connection example

In this post 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.

There is a simple code snippet to check the name of the current database connection. and if not, it will return ‘none’. 

Laravel database configuration is stored inside config/database.php. The list of database configurations is listed inside the file. By default, you need to tell laravel which database you are going to make use of.

Let’ see example of laravel check database connection

 /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

The .env file has the environment configuration for your database file as shown below

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testDB
DB_USERNAME=root
DB_PASSWORD=

When you start working with a database make sure to enter all the valid details in the .env file for database connection to mysql.

If you need to check database connection exists or not in laravel. Then will give you multiple examples using DB PDO and DB getDatabaseName().

1. Laravel check database connection using DB PDO and DB getDatabaseName()
Example 1:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class IndexController extends Controller
{

    public function index(Request $request)
    {
        if (DB::connection()->getDatabaseName()) {
            $databaseName = DB::connection()->getDatabaseName();
            dd("Connect successfully to database " . $databaseName . ".");
        }
    }
  
}
Output:
Connected successfully to database "testDB".
Example 2:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Exception;

class IndexController extends Controller
{

     public function index(Request $request)
     {
        try {
            DB::connection()->getPDO();
            $databaseName = DB::connection()->getDatabaseName();
            dd("Connect successfully to database " . $databaseName . ".");
        } catch (Exception $e) {
            dd("None");
        }
    }
}

Explanation:

  • DB::connection()->getPDO(); is used to get the PDO instance, which indicates the connection successful.
  • If an exception occurs, it catches and returns an error message.
2. Laravel check database connection using middleware

If you want to check the connection before each request, you can create and integrate middleware.

php artisan make:middleware CheckConnectionDatabase

Add this code the handle method of the middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use DB;
use Illuminate\Http\Request;

class CheckConnectionDatabase
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            DB::connection()->getPdo();
        }catch (Exception $e) {
            return response()->json(['error' => 'Database connection failed!'], 500);
        }
        return $next($request);
    }
}

Usage: Register this middleware in the app\Http\Kernel.php file, and Laravel will check the connection before any request.

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *