The Laravel framework is great for swiftly building applications. It allows you to connect to a database rapidly. If you’re working on a local development project, you’ll probably need to check at some point—possibly when you’re troubleshooting—to see if the application is connected to a database.
If you need to check database connection exists or not in laravel. Then I will give you simple two examples using DB PDO and DB getDatabaseName()
.
How to check your Laravel database connection
A line of code will return “none” if the name of the current database connection cannot be identified. There are two methods.
- Anywhere in a Blade template or PHP file will do.
- Place it in a random file and
dump()
it to the dump server
1. Echo the Laravel database name in Blade/PHP
The 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';
}
?>
2. Using the dump server to check this
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.
Thank you for reading this article.