简体   繁体   中英

Using two databases in Laravel

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM