How to check your Laravel database connection - TechvBlogs

How to check your Laravel database connection

Here is a simple guide to check your Laravel application database connection.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

3 weeks ago

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.

  1. Anywhere in a Blade template or PHP file will do.

  2. 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.

Read Also: Add Column After A Column In Laravel Migration

Comments (0)

ServerAvatar
Multiple sites on a single VPS/VM/Server Deploy PHP sites on cloud in minutes, simple as that!
ServerAvatar
Generate Free SSL Certificate - SSLForWeb

Generate Free SSL Certificate

  • 90-Day Certificates
  • SSL Monitoring
  • Wildcard Certificates
  • Multiple Domains
  • Certificate Management
  • Expiration Reminders

Comment


Note: All Input Fields are required.