简体   繁体   中英

How i can change .env variables in Laravel 6.0 by controller?

我正在 Laravel 上创建一个系统,我想授予管理员更改某些 .env 变量(如邮件设置(服务器或端口)等)的权限。我该怎么做?

I have created a method changeEnv for same:

public function changeEnv($data = array()){
      if(count($data) > 0){

        // Read .env-file
        $env = file_get_contents(base_path() . '/.env');

        // Split string on every " " and write into array
        $env = preg_split('/\s+/', $env);;

        // Loop through given data
        foreach((array)$data as $key => $value){

          // Loop through .env-data
          foreach($env as $env_key => $env_value){

            // Turn the value into an array and stop after the first split
            // So it's not possible to split e.g. the App-Key by accident
            $entry = explode("=", $env_value, 2);

            // Check, if new key fits the actual .env-key
            if($entry[0] == $key){
              // If yes, overwrite it with the new one
              $env[$env_key] = $key . "=" . $value;
            } else {
              // If not, keep the old one
              $env[$env_key] = $env_value;
            }
          }
        }

        // Turn the array back to an String
        $env = implode("\n", $env);

        // And overwrite the .env with the new data
        file_put_contents(base_path() . '/.env', $env);

        return true;
      } else {
        return false;
      }
    }

usage :

$this->changeEnv(['lastEvaluatedKeyAU' => 'randomID-or-randomString']);

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