Check Database Connection Laravel 9

Of course, you need to check database connection Laravel 9 before starting your database driven Laravel App.

Check Database Connection Laravel 9

Check Database Connection Laravel

Indeed, you may check database connection in Laravel 9 but you need to confirm database connection in Laravel before it. Therefore, we will start from the default database connection name in Laravel.

1. Default Database Connection Name

Most importantly, you can setup database name in .env file. Further, you can find .env file in Laravel app root folder. Please follow the below to confirm default database connection name.

1.1 Environment Configuration File – .env File

  • DB_CONNECTION – Firstly, open .env file and then navigate to DB_CONNECTION to confirm your database settings.
    • DB_DATABASE – Here, db_database is the default database name for your Laravel App.

Furthermore, you may found in online tutorials that Laravel config/database.php can be used to setup database connection. Let’s explore it as well.

1.2 Database File Connection – database.php File

In fact, You can see in config/database.php file that default database connection name has something pointing to environment file. You can find a default string, ‘default’ => env(‘DB_CONNECTION’, ‘mysql’), with description as below.

Here you may specify which of the database connections below you wish to use as your default connection for all database work. Of course, you may use many connections at once using the Database library.

Furthermore, ‘default’ => env(‘DB_CONNECTION’, ‘mysql’) is already getting the default database connection name from .env file.

2. Laravel Database Connection in Artisan Console

In fact, I use artisan console to confirm database connection on the very first stage. So, let’s start to confirm the database connection using php artisan tinker command.

  • Firstly, open a Terminal (Command prompt, Powershell, Shell, Putty etc.) and navigate to root Laravel App.
  • Secondly, I run php artisan tinker command to start tinker to check database connection.
  • Thirdly, You can also use DB::connection()->getPdo(); in artisan console to confirm the database connection.
php artisan tinker command

3. Laravel Database Connection in Blade/Controller

In addition, you can use the code below in your blade or controller to check the database error. So, you can copy the code below in your blade or controller file.

use Illuminate\Support\Facades\DB;

try {
    DB::connection()->getPdo();
} catch (\Exception $e) {
    die("Could not connect to the database.  Please check your configuration. error:" . $e );
}

4. Laravel Database Connection Troubleshooting

In fact, you may faced sometimes that your database settings are all confirmed but you are still unable to connect Laravel database. You can read SQLSTATE [HY000] [1049] Unknown database ‘laravel’ to troubleshoot the database connection issue.

Laravel Documents

Share

You may also like...