Hello Geek, Laravel is an excellent framework for quickly developing applications. It enables you to quickly connect to a database. If you’re developing locally, you may need to confirm that the application is connected to a database, for example, when debugging.
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()
.
There is a simple code snippet to check the name of the current database connection, and if not, it will return ‘none’. There are two ways to it:
- Put it somewhere in a Blade template or PHP-file (recommended for one-time debugging)
- Put it in a random file and
dump()
it to the dump-server (recommended for all other use cases)
Echo the Laravel database name in Blade/PHP
The simplest way it to place the following script in a Blade or PHP file. This will output the name of the database or return ‘none’ if there is no connection.
<strong>Database Connected: </strong>
<?php
try {
\DB::connection()->getPDO();
echo \DB::connection()->getDatabaseName();
} catch (\Exception $e) {
echo 'None';
}
?>
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.
All the best nerd!