Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling DB failed to connect in laravel?

Tags:

I was wondering if there was a way where I can display a custom view when laravel fails to connect to the database? I have tried googling an answer for this but it really doesn't display anything useful.

I currently get:

Whoops, looks like something went wrong.

2/2
QueryException in Connection.php line 770:
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) (SQL: select * from `users` where `users`.`id` = 1 limit 1)

Thanks.

like image 659
Ashkru Avatar asked Jan 02 '17 09:01

Ashkru


People also ask

How check DB connected or not in Laravel?

Echo the Laravel database name in Blade/PHP This will output the name of the database or return 'none' if there is no connection. If you view it in the browser, it gives you the name of the connected database. Checking whether the application is connected to a Laravel database.

How does Laravel connect to database?

Laravel makes connecting with databases and running queries extremely simple. The database configuration file is app/config/database. php . In this file you may define all of your database connections, as well as specify which connection should be used by default.

Does Laravel close database connection?

It disconnects at the end of The Script. Laravel isn't using persistent connections and they can be bad at times anyway please dig into the PHP manual and there's a in-depth explaination of when and when not to use.


1 Answers

In your app/Exceptions/Handler.php, go to render method . You can add the following exception checking to handle query and pdo exception

    if ($e instanceof \Illuminate\Database\QueryException) {
        dd($e->getMessage());
        //return response()->view('custom_view');
    } elseif ($e instanceof \PDOException) {
        dd($e->getMessage());
        //return response()->view('custom_view');
    }

Replace dd($e->getMessage()); with your custom code.

like image 59
shoieb0101 Avatar answered Sep 25 '22 09:09

shoieb0101