For details about how Laravel calls different configuration files in different environments, refer to: Reproduced from Yuansir-web Cainiao | LAMP learning Notes
Link: Laravel calls different configuration files in different environments
How does Laravel call different configuration files in different environments? There are a lot of questions about the community. There should be many methods to implement it elegantly. I usually use two methods to set environment variables or write the environment values. if you do not know whether the env file is elegant, please refer to the more elegant method.
1. set environment variables. for example, there are two environments: local development and online development.
Local Configuration of php-fpm (for example, with php-fpm instead of apache), for example, environment variable for DEV_ENV, modify php-fpm.conf
env[DEV_ENV]=local
Then, set the environment variables of the local system.
echo "export DEV_ENV=local" >> /etc/profilesource /etc/profile
Let Laravel introduce the corresponding configuration file and add the following code to bootstrap/app. php.
$environment = getenv('DEV_ENV') ? '.' . getenv('DEV_ENV') : '';$app->loadEnvironmentFrom('.env'.$environment);
Create in laravel project. env. local, where the configuration is the configuration of the local development environment ,. env is an online environment. of course, you can create other configuration files, such. env. develop ,. env. preview and so on. add the configuration file and environment variables according to the actual situation. different configurations are called according to the environment variables in different environments. The advantage of this method is that you do not need to set the environment variable DEV_ENV after the project is launched. Therefore, the launch project automatically calls the configuration in. env.
2. write the name of the current environment in. env. for example, there are two environments: local development and online development.
Clear the. env file and write only the first line to the current running environment, such as local
Create a new. local. env and. production. env, respectively, to write local and online configuration items.
Add the following code to bootstrap/app. php:
$env = $app->detectEnvironment(function () { $environmentPath = __DIR__ . '/../.env'; $setEnv = trim(file_get_contents($environmentPath)); if(file_exists($environmentPath)) { putenv("APP_ENV=$setEnv"); if(getenv('APP_ENV') && file_exists(__DIR__ . '/../.' . getenv('APP_ENV') . '.env')) { Dotenv::load(__DIR__ . '/../', '.' . getenv('APP_ENV') . '.env'); } }});
In this way, you can call the corresponding configuration file based on the value written by the. env file.
If you have more elegant methods, please feel free to advise.