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

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

    Based on josh's answer. I needed a way to replace the value of a key inside the .env file.

    But unlike josh's answer, I did not want to depend on knowing the current value or the current value being accessible in a config file at all.

    Since my goal is to replace values that are used by Laravel Envoy which doesn't use a config file at all but instead uses the .env file directly.

    Here's my take on it:

    public function setEnvironmentValue($envKey, $envValue)
    {
        $envFile = app()->environmentFilePath();
        $str = file_get_contents($envFile);
    
        $oldValue = strtok($str, "{$envKey}=");
    
        $str = str_replace("{$envKey}={$oldValue}", "{$envKey}={$envValue}\n", $str);
    
        $fp = fopen($envFile, 'w');
        fwrite($fp, $str);
        fclose($fp);
    }
    

    Usage:

    $this->setEnvironmentValue('DEPLOY_SERVER', 'forge@122.11.244.10');
    

提交回复
热议问题