I have faced RDS connection issues a lot. Cause AWS RDS used a different env variable rather than the Laravel default one for MySQL connection.

So what is the best way to resolve the issue?

Add this code on the top of your /config/database.php

use Illuminate\Support\Str;

define('RDS_HOSTNAME', (isset($_SERVER['RDS_HOSTNAME'])) ? $_SERVER['RDS_HOSTNAME'] : null);
define('RDS_USERNAME', (isset($_SERVER['RDS_USERNAME'])) ? $_SERVER['RDS_USERNAME'] : null);
define('RDS_PASSWORD', (isset($_SERVER['RDS_PASSWORD'])) ? $_SERVER['RDS_PASSWORD'] : null);
define('RDS_DB_NAME', (isset($_SERVER['RDS_DB_NAME'])) ? $_SERVER['RDS_DB_NAME'] : null);

And change your MySQL connection to:

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => (RDS_HOSTNAME) ? RDS_HOSTNAME : env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => (RDS_DB_NAME) ? RDS_DB_NAME : env('DB_DATABASE', 'forge'),
            'username' => (RDS_USERNAME) ? RDS_USERNAME : env('DB_USERNAME', 'forge'),
            'password' => (RDS_PASSWORD) ? RDS_PASSWORD : env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => false,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

Great! You are done!

If we config like this way then we don’t need to change our .env variable according to RDS. We can use the Laravel default one so local, stage & live work perfectly with these same .env variables for any kind of deployment.

Cheers!!

https://rdevs.xyz
Do you like Ashiqur Rahman's articles? Follow on social!
Comments to: Config RDS connection for Laravel the right way | Best practices

Your email address will not be published.

Attach images - Only PNG, JPG, JPEG and GIF are supported.

Login

Welcome to rDevs

Brief and amiable onboarding is the first thing a new user sees in the theme.
Join rDevs

start writing