How to check if connected to database in Laravel 4?

前端 未结 3 1999
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 19:03

How can I check if laravel is connected to the database? I\'ve searched around and I can\'t find anything that would tell me how this is done.

相关标签:
3条回答
  • 2021-02-01 19:28

    working :) -

    Just added this code to app/filters.php

    App::error(function(PDOException $exception)
    {
        Log::error("Error connecting to database: ".$exception->getMessage());
    
        return "Error connecting to database";
    });
    
    0 讨论(0)
  • 2021-02-01 19:29

    You can Use the following code :

    try{
       DB::connection()->getDatabaseName();
    }catch(Exception $e){
       echo $e->getMessage();
    }
    
    0 讨论(0)
  • 2021-02-01 19:39

    You can use

    if(DB::connection()->getDatabaseName())
    {
       echo "Connected sucessfully to database ".DB::connection()->getDatabaseName().".";
    }
    

    It will give you the database name for the connected database, so you can use it to check if your app is connected to it.

    But... Laravel will only connect to database once it needs something from database and, at the time of a connection try, if it finds any errors it will raise a PDOException, so this is what you can do to redirect your user to a friendly page:

    App::error(function(PDOException $exception)
    {
        Log::error("Error connecting to database: ".$exception->getMessage());
    
        return "Error connecting to database";
    });
    

    Add this to your app/filters.php file.

    In my opinion, you don't really need to check if it is connceted or not, just take the proper action in the exception handling closure.

    0 讨论(0)
提交回复
热议问题