Open In App

Laravel | MySQL Database Connection

The database is an important element in any application. Laravel by default provides the support of MySQL. MySQL is a well known, open-source RDBMS (Relational Database Management System).

Process for Connecting to the Database:



Custom Error Message: If you don’t want Laravel to handle it and give a predefined message then you can use try . . . catch block as shown below or can directlyreplace the step 6 codes with this lines of code:




<!DOCTYPE html>
<html>
<head>
    <title>GeeksforGeeks</title>
    <style>
        div {
            font-size: 22px;
        }
    </style>
</head>
<body>
    <div>
        <?php                    
            try {
                if(DB::connection()->getPdo())
                {
                    echo "Successfully connected to the database => "
                                  .DB::connection()->getDatabaseName();
                }
            }
            catch (Exception $e) {
                echo "Unable to connect";
            }
        ?>
    </div>
</body>
</html>

Here, if unsuccessful then will print the message written in the catch block:

Reference: https://laravel.com/docs/6.x/database


Article Tags :