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

前端 未结 14 1022
忘掉有多难
忘掉有多难 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:47

    tl;dr

    Based on vesperknight's answer I created a solution that doesn't use strtok or env().

    private function setEnvironmentValue($envKey, $envValue)
    {
        $envFile = app()->environmentFilePath();
        $str = file_get_contents($envFile);
    
        $str .= "\n"; // In case the searched variable is in the last line without \n
        $keyPosition = strpos($str, "{$envKey}=");
        $endOfLinePosition = strpos($str, PHP_EOL, $keyPosition);
        $oldLine = substr($str, $keyPosition, $endOfLinePosition - $keyPosition);
        $str = str_replace($oldLine, "{$envKey}={$envValue}", $str);
        $str = substr($str, 0, -1);
    
        $fp = fopen($envFile, 'w');
        fwrite($fp, $str);
        fclose($fp);
    }
    

    Explanation

    This doesn't use strtok that might not work for some people, or env() that won't work with double-quoted .env variables which are evaluated and also interpolates embedded variables

    KEY="Something with spaces or variables ${KEY2}"
    

提交回复
热议问题