In this example, we will check the database connection in Laravel. Before starting create a new Laravel application and start your database services like XAMPP or WAMPP and change database credentials in .env file.
Here, we will check database is connected and get an active database name using DB helper. For checking database exists or not in laravel then you can use DB PDO method.
Check Database Connection In Laravel
In this method, we will check whether our application is connected to the database or not. If connected then we will print name of the database.
Let's take an example to check Laravel application is connected or not:
In the above example, first of all, we have used the DB facade and getPDO() method which will check the database connection in the laravel application. If an application is connected to a database then it will print database name.
Get Connected Database Name In Laravel
Here, we will get the database name using DB helper. For that, we will use connection() method to get a current connection using the DB facade and getDatabaseName() method to get database name.
Conclusion
In this article, we have taken two examples to check database name or connections in Laravel. The first method will check the database connection from the PDO connection object while in the second method, we get the name of the database using any driver.