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

前端 未结 14 929
忘掉有多难
忘掉有多难 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;
    
    }
    
    0 讨论(0)
  • 2020-12-01 09:57

    More simplified:

    public function putPermanentEnv($key, $value)
    {
        $path = app()->environmentFilePath();
    
        $escaped = preg_quote('='.env($key), '/');
    
        file_put_contents($path, preg_replace(
            "/^{$key}{$escaped}/m",
            "{$key}={$value}",
            file_get_contents($path)
        ));
    }
    

    or as helper:

    if ( ! function_exists('put_permanent_env'))
    {
        function put_permanent_env($key, $value)
        {
            $path = app()->environmentFilePath();
    
            $escaped = preg_quote('='.env($key), '/');
    
            file_put_contents($path, preg_replace(
                "/^{$key}{$escaped}/m",
               "{$key}={$value}",
               file_get_contents($path)
            ));
        }
    }
    
    0 讨论(0)
提交回复
热议问题