hashbrown
hashbrown

Reputation: 3516

Laravel Secondary database connection does not work

I have one MySQL database connection in config/database.php as below, and it is working fine.

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],

I am trying to define another alternate connection (for testing purposes) as below. (Same host but different database):

'mysql_testing' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE_TEST', 'forge'),
    'username' => env('DB_USERNAME_TEST', 'forge'),
    'password' => env('DB_PASSWORD_TEST', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],

where DB_DATABASE_TEST, DB_USERNAME_TEST and DB_PASSWORD_TEST are defined in .env as below:

DB_DATABASE_TEST=db_other
DB_USERNAME_TEST=usr_other
DB_PASSWORD_TEST=secret

However, this second connection does not work. In Tinker, if I try to use the new connection:

DB::connection('mysql_testing')->getPdo()
InvalidArgumentException with message 'Database [mysql_testing] not configured.'

If I try to check the config values, mysql works but the new connection mysql_testing returns null.

Config::get('database.connections.mysql')
[
 "driver" => "mysql",
 "host" => "127.0.0.1",
 "port" => "3306",
 "database" => "***",
 "username" => "***",
 "password" => "***",
 "charset" => "utf8",
 "collation" => "utf8_unicode_ci",
 "prefix" => "",
 "strict" => false,
 "engine" => null,
]

Config::get('database.connections.mysql_testing')
null

Any idea how may I debug this issue?

Upvotes: 3

Views: 567

Answers (1)

hashbrown
hashbrown

Reputation: 3516

This was happening because Laravel 5 automatically caches the config values. Therefore, even if we change the config/database.php values, the changes wouldn't take effect as Laravel will continue to read it from cache.

There's a way to clear the cache. But this will not clear config cache

php artisan cache:clear  

Luckily, there is a different artisan command for that. To clear the config cache you need to use

php artisan config:clear  

Upvotes: 1

Related Questions