In this tutorial, we will learn how to check your Laravel database connection. We will give you simple two examples using DB PDO and DB getDatabaseName()
.
A line of code will return "none" if the name of the current database connection cannot be identified. There are two methods.
dump()
it to the dump serverThe following script should be added to a Blade or PHP file for the simplest solution. If there is no connection, this will return "none" or the name of the database.
<strong>Database Connected: </strong>
<?php
try {
\DB::connection()->getPDO();
echo \DB::connection()->getDatabaseName();
} catch (\Exception $e) {
echo 'None';
}
?>
However, you could also put it in a controller or the boot()
function in the app/Providers/AppServiceProvider.php
file, in addition to Blade or PHP. Personally, I think it ought to go in the boot()
procedure.
try {
\DB::connection()->getPDO();
dump('Database connected: ' . \DB::connection()->getDatabaseName());
} catch (\Exception $e) {
dump('Database connected: ' . 'None');
}
Using the php artisan dump-server
command to check the database connection.