Laravel 5.1 - Checking a Database Connection
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Laravel is one of the most popular PHP frameworks, known for its elegance and robust features. One of these powerful features is the built-in database support through Eloquent ORM, which helps you work with various database systems seamlessly. However, what if you want to check if a specific database connection has been established successfully? This guide aims to provide a comprehensive solution for checking your Laravel 5.1 database connections.
Database Connections in Laravel
In Laravel, connecting to various databases is simple using the config/database.php file. Here you can define multiple database connections with different configurations and parameters for each connection. For example, if you have three instances of MySQL on different machines and want to use them in your application, you might have defined these as:
'mysql1' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laradb_1',
'username' => 'root',
'password' => '',
],
'mysql2' => [
'driver' => 'mysql',
'host' => '192.168.0.1',
'database' => 'laradb_2',
'username' => 'root',
'password' => '',
],
'mysql3' => [
'driver' => 'mysql',
'host' => 'mysql-third.example.com',
'database' => 'laradb_3',
'username' => 'root',
'password' => '',
]
Now, the following question arises: Can I check whether these connections are established? Unfortunately, the Laravel documentation does not directly address this issue. But you can achieve it using some simple code and a custom function.
Checking Database Connections
To create a utility helper class that checks your database connection, first create an App\Helpers\DatabaseConnectionsHelper class in your project:
Next, you will need to create a function that returns the PDO object from the given database connection. Add this function to your helper class:
With this function, you can easily get the PDO object for a given connection. Now to check if a database connection is established, use another function in your helper class:
getConnectionPdo($connectionName)) ? true : false;
}
}
Finally, you can use this helper in your Laravel application as follows:
// In your controller or service class
use App\Helpers\DatabaseConnectionsHelper;
$database1 = new DatabaseConnectionsHelper();
$isConnectedToDatabase1 = $database1->checkDatabaseConnection('mysql1');
if ($isConnectedToDatabase1) {
// Use database 1 for your tasks
} else if ($isConnectedToDatabase2 = $database1->checkDatabaseConnection('mysql2')) {
// Use database 2 for your tasks
} ...
In conclusion, Laravel provides powerful functionality to interact with databases but does not directly address the issue of checking database connections. Using helper functions and custom code, however, you can easily verify if a specific database connection is established or not. Remember to handle any potential exceptions gracefully in your application for optimal performance.