How to use different database on development than

2019-07-29 05:50发布

问题:

Becouse I developing on my notebook and on my destkop, too I want to use an sql server what I can connect anytime.

I want to connect to this when I'm on the development enviroment and use an other when I'm on production. How can I achieve this?

I tried this in the config/database:

if('env' == 'development'){ 
    $host = 'mysqlserver.alias.com'; 
    $database = 'mydb'; 
    $username = 'myuname'; 
    $password = 'mypwd'; 
} else { 
    $host = whatsintheenv; 
    $database = whatsintheenv; 
    $username = whatsintheenv; 
    $password = whatsintheenv;    
} 

回答1:

This should be handled by your environment configuration via the .env file.

If you don't have a .env file yet, make a copy of .env.example. In there, you'll find these settings:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Simply modify these values to connect to the correct database server.

The .env file is excluded from source control, so your notebook and your desktop can have different contents in this file.



回答2:

In Laravel you can check environment by:

if (App::environment('local')) {
  // The environment is local
}

if (App::environment(['local', 'staging'])) {
   // The environment is either local OR staging...
}


回答3:

Laravel makes use of the PHP dotenv library - https://github.com/vlucas/phpdotenv.

This means you'll want to create a .env file on each of your machines with the connection that you want to use. Then in your code, you can load these values using App:environment('ENV_VALUE').