一.把.env文件另存为.env.local为本地开发环境,添加APP_ENV=local,
另存为.env.testing为测试环境,添加APP_ENV=testing,
另存为.env.production为生产环境,添加APP_ENV=production,
同理可以设置N多个...
二.打开项目下bootstrap下的app.php ,加入如下代码:
//.env配置多环境
$env = $app->detectEnvironment(function () {
$environmentPath = __DIR__ . '/../';//项目根目录,.env所在目录
$setEnv = trim(file_get_contents($environmentPath.'.env'));//获取.env文件内容
if(file_exists($environmentPath)) {
putenv("APP_ENV=$setEnv");
if(getenv('APP_ENV') && file_exists($environmentPath.'.' . getenv('APP_ENV') . '.env')) {
Dotenv::load($environmentPath, '.' . getenv('APP_ENV') . '.env');//配置的.env文件存在则加载
}
}
});
image.png
以上代码优化如下:
//.env配置多环境
$env = $app->detectEnvironment(function () use($app) {
$environmentPath = $app->environmentPath();//.env所在目录
// putenv("APP_ENV=$setEnv");//写入env //getenv('APP_ENV');//获取env
$setEnv = trim(file_get_contents($environmentPath.'/.env'));//获取.env文件内容
if(file_exists($environmentPath)) {
$app->loadEnvironmentFrom('.env.'.$setEnv);
}
});
三.把.env文件清空,里面写入local,testing,production等,则可以切换对应的环境。
继续优化,把这段代码移到index.php文件中,如下:
$app = require_once __DIR__.'/../bootstrap/app.php';
# .env配置多环境
$app->detectEnvironment(function () use($app) {
$envName = trim(file_get_contents($app->environmentPath().'/.env'));//获取默认env文件配置要加载的env文件名
$app->loadEnvironmentFrom('.env.'.$envName);
});
继续优化成一行代码,把index.php忽略git版本控制,实现多环境互不干扰!
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->loadEnvironmentFrom('.env.online');# .env配置多环境,只此一行
在Providers/AppServiceProvider中的register方法判断环境加载所需服务!
if ($this->app->environment() !== 'online') {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}