Search code examples
phpmysqllaraveldie

Database connection and die issue


 if(DB::connection()->getDatabaseName()){
        $data = User::get(['id','first_name','last_name']);
        return View::make('index')->with('data',$data);
    }
    else{
        $request->session()->put('error','Could not connect to the database.  Please check your configuration.');
        return view::make('errors.503');  
    }   

My else part is not working while DB is not connect. How to handle all DB connection and die exception in laravel 5.2


Solution

  • DB::connection()->getDatabaseName() checks the name from your configuration, that must be the reason why always evaluates to true

    Try instead DB::connection()->getPdo();, it will throw an exception (use try/catch) if fails.

    edit:

    try {
        DB::connection()->getPdo();
        $data = User::get(['id','first_name','last_name']);
        return View::make('index')->with('data',$data);
    } catch (\PDOException $e) {
        $request->session()->put('error','Could not connect to the database.  Please check your configuration.');
        return view::make('errors.503');  
    }