2

I wish to hide critical server access information as Laravel recommended, so I have setup config/database.php and .env as below, but these couldn't connect each one. which line was wrong?

Laravel version: 5.4

config/database.php

'connections' => [
    'master_db' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST_MASTER', '127.0.0.1'),
        'port' => env('DB_PORT_MASTER', '3306'),
        'database' => env('DB_DATABASE_MASTER'),
        'username' => env('DB_USERNAME_MASTER'),
        'password' => env('DB_PASSWORD_MASTER'),
        'unix_socket' => env('DB_SOCKET_MASTER'),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'slave_db' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST_SLAVE', '192.1.0.2'),
        'port' => env('DB_PORT_SLAVE', '3306'),
        'database' => env('DB_DATABASE_SLAVE'),
        'username' => env('DB_USERNAME_SLAVE'),
        'password' => env('DB_PASSWORD_SLAVE'),
        'unix_socket' => env('DB_SOCKET_SLAVE'),
        'charset' => 'latin1',
        'collation' => 'latin1_general_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
]

.env

DB_CONNECTION=master_db
DB_HOST_MASTER=127.0.0.1
DB_PORT_MASTER=3306
DB_DATABASE_MASTER=db_master
DB_USERNAME_MASTER=user_master
DB_PASSWORD_MASTER=passwordmaster

DB_CONNECTION=slave_db
DB_HOST_SLAVE=192.1.0.2
DB_PORT_SLAVE=3307
DB_DATABASE_SLAVE=db_slave
DB_USERNAME_SLAVE=user_slave
DB_PASSWORD_SLAVE=passwordslave
2
  • 1
    The keys in your .env file should be unique, otherwise only the first value is used. So you have DB_CONNECTION listed twice, but only the first value (master) will be used by Laravel, and it won’t connect to the database because you don’t have a key named master in your config/database.php file. Commented Oct 26, 2017 at 8:18
  • @MartinBean, Hi-! I modified question. Commented Oct 26, 2017 at 8:21

1 Answer 1

2

If you want use like upper config/database.php file style, then .env file recommend as below as simple. :)

DB_CONNECTION=master_db
DB_HOST_MASTER=127.0.0.1
DB_PORT_MASTER=3306
DB_DATABASE_MASTER=db_master
DB_USERNAME_MASTER=user_master
DB_PASSWORD_MASTER=passwordmaster

// DB_CONNECTION=slave_db <------ no needed this line
DB_HOST_SLAVE=192.1.0.2
DB_PORT_SLAVE=3307
DB_DATABASE_SLAVE=db_slave
DB_USERNAME_SLAVE=user_slave
DB_PASSWORD_SLAVE=passwordslave
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.