2015-08-31 47 views

回答

16

有没有内置的方式来做到这一点。如果您真的想更改.env文件的内容,则必须将某种字符串替换与PHP的文件写入方法结合使用。对于一些灵感,你应该看看key:generate命令:KeyGenerateCommand.php:文件的路径是建立和存在的检查

$path = base_path('.env'); 

if (file_exists($path)) { 
    file_put_contents($path, str_replace(
     'APP_KEY='.$this->laravel['config']['app.key'], 'APP_KEY='.$key, file_get_contents($path) 
    )); 
} 

后,命令只是替换APP_KEY=[current app key]APP_KEY=[new app key]。你应该可以用其他变量进行相同的字符串替换。
最后但并非最不重要我只是想说,让用户更改.env文件可能不是最好的主意。对于大多数自定义设置,我建议将它们存储在数据库中,但是,如果设置本身是连接到数据库所必需的,那么这显然是一个问题。

1

我有同样的问题,并已创建下面

public static function changeEnvironmentVariable($key,$value) 
{ 
    $path = base_path('.env'); 

    if(is_bool(env($key))) 
    { 
     $old = env($key)? 'true' : 'false'; 
    } 

    if (file_exists($path)) { 
     file_put_contents($path, str_replace(
      "$key=".$old, "$key=".$value, file_get_contents($path) 
     )); 
    } 
} 
+0

$ old可能未定义 – sgotre

1

又一实现的功能,如果你有这样的:

A = B#这是一个有效项

在你的.env文件中

public function updateEnv($data = array()) 
{ 
    if (!count($data)) { 
     return; 
    } 

    $pattern = '/([^\=]*)\=[^\n]*/'; 

    $envFile = base_path() . '/.env'; 
    $lines = file($envFile); 
    $newLines = []; 
    foreach ($lines as $line) { 
     preg_match($pattern, $line, $matches); 

     if (!count($matches)) { 
      $newLines[] = $line; 
      continue; 
     } 

     if (!key_exists(trim($matches[1]), $data)) { 
      $newLines[] = $line; 
      continue; 
     } 

     $line = trim($matches[1]) . "={$data[trim($matches[1])]}\n"; 
     $newLines[] = $line; 
    } 

    $newContent = implode('', $newLines); 
    file_put_contents($envFile, $newContent); 
} 
1

更新Erick的回答考虑$old值覆盖sting,bool和空值。

public static function changeEnvironmentVariable($key,$value) 
{ 
    $path = base_path('.env'); 

    if(is_bool(env($key))) 
    { 
     $old = env($key)? 'true' : 'false'; 
    } 
    elseif(env($key)===null){ 
     $old = 'null'; 
    } 
    else{ 
     $old = env($key); 
    } 

    if (file_exists($path)) { 
     file_put_contents($path, str_replace(
      "$key=".$old, "$key=".$value, file_get_contents($path) 
     )); 
    } 
}