How to set .env values in laravel programmatically on the fly

前端 未结 14 1009
忘掉有多难
忘掉有多难 2020-12-01 09:05

I have a custom CMS that I am writing from scratch in Laravel and want to set env values i.e. database details, mailer details, general configuration, etc from

14条回答
  •  我在风中等你
    2020-12-01 09:57

    Based on totymedli's answer.

    Where it is required to change multiple enviroment variable values at once, you could pass an array (key->value). Any key not present previously will be added and a bool is returned so you can test for success.

    public function setEnvironmentValue(array $values)
    {
    
        $envFile = app()->environmentFilePath();
        $str = file_get_contents($envFile);
    
        if (count($values) > 0) {
            foreach ($values as $envKey => $envValue) {
    
                $str .= "\n"; // In case the searched variable is in the last line without \n
                $keyPosition = strpos($str, "{$envKey}=");
                $endOfLinePosition = strpos($str, "\n", $keyPosition);
                $oldLine = substr($str, $keyPosition, $endOfLinePosition - $keyPosition);
    
                // If key does not exist, add it
                if (!$keyPosition || !$endOfLinePosition || !$oldLine) {
                    $str .= "{$envKey}={$envValue}\n";
                } else {
                    $str = str_replace($oldLine, "{$envKey}={$envValue}", $str);
                }
    
            }
        }
    
        $str = substr($str, 0, -1);
        if (!file_put_contents($envFile, $str)) return false;
        return true;
    
    }
    

提交回复
热议问题