Discover If Your Laravel Database Exists!

 How to check Database exist or not in Laravel

Discover-If-Your-Laravel-Database-Exists

In this article we will learn how to check database exist or not in Laravel. Laravel provides lots of built-in functions to make our database queries easier , to check database connection with Laravel we will use one of the database query builder method. You can also use other methods to check database connect , other data fetching queries and using of schema methods to check table and column exist or not .
You can check the following example to check database exist or not in Laravel .

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Artisan;
use DB;

class HomeController extends Controller
{
    public function checkDbExist()
    {
        try{
            $db_name = "devtrigger";
            $query = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME =  ?";
            $database = DB::select($query, [$db_name]);
            if (!empty($database)) {
                return 'DB exist';
            } else {
                return 'DB does not exist';
            }
        }
        catch(\Exception $e){
            return false;
        }
    }
}


Previous Post Next Post

Contact Form