26

I want to create a Laravel web app that allows an admin user to change some variables(such as database credentials) in the .env file using the web backend system. But how do I save the changes?

10 Answers 10

42

There is no built in way to do that. If you really want to change the contents of the .env file, you'll have to use some kind of string replace in combination with PHP's file writing methods. For some inspiration, you should take a look at the key:generate command: KeyGenerateCommand.php:

$path = base_path('.env');

if (file_exists($path)) {
    file_put_contents($path, str_replace(
        'APP_KEY='.$this->laravel['config']['app.key'], 'APP_KEY='.$key, file_get_contents($path)
    ));
}

After the file path is built and the existence is checked, the command simply replaces APP_KEY=[current app key] with APP_KEY=[new app key]. You should be able to do the same string replacement with other variables.
Last but not least I just wanted to say that it might isn't the best idea to let users change the .env file. For most custom settings I would recommend storing them in the database, however this is obviously a problem if the setting itself is necessary to connect to the database.

2
  • Fails in my window environment. Any solution for that. Commented Dec 11, 2018 at 18:06
  • when i debug $this->laravel['config'] gives error it says error evaluating code
    – Sami
    Commented Dec 9, 2020 at 7:27
9

Yet another implementation, in case you have something like:

A = B #this is a valid entry

In your .env file

public function updateEnv($data = array())
{
    if (!count($data)) {
        return;
    }

    $pattern = '/([^\=]*)\=[^\n]*/';

    $envFile = base_path() . '/.env';
    $lines = file($envFile);
    $newLines = [];
    foreach ($lines as $line) {
        preg_match($pattern, $line, $matches);

        if (!count($matches)) {
            $newLines[] = $line;
            continue;
        }

        if (!key_exists(trim($matches[1]), $data)) {
            $newLines[] = $line;
            continue;
        }

        $line = trim($matches[1]) . "={$data[trim($matches[1])]}\n";
        $newLines[] = $line;
    }

    $newContent = implode('', $newLines);
    file_put_contents($envFile, $newContent);
}
0
6

Update Erick's answer with consideration of $old values covering sting, bool and null values.

public static function changeEnvironmentVariable($key,$value)
{
    $path = base_path('.env');

    if(is_bool(env($key)))
    {
        $old = env($key)? 'true' : 'false';
    }
    elseif(env($key)===null){
        $old = 'null';
    }
    else{
        $old = env($key);
    }

    if (file_exists($path)) {
        file_put_contents($path, str_replace(
            "$key=".$old, "$key=".$value, file_get_contents($path)
        ));
    }
}
0
4

To extend on lukasgeiter's and other's answer above, using regex to match the .env would be better, , as unlike app.key, the variable to put in .env may not be in the config.

Below is the code I used when experimenting on custom artisan command. This code generates a key for XChaCha encryption (XCHACHA_KEY=?????):


$path = base_path('.env');
if (file_exists($path)) {
    //Try to read the current content of .env
    $current = file_get_contents($path);   

    //Store the key
    $original = [];
    if (preg_match('/^XCHACHA_KEY=(.+)$/m', $current, $original)) { 
    //Write the original key to console
        $this->info("Original XChaCha key: $original[0]"); 

    //Overwrite with new key
        $current = preg_replace('/^XCHACHA_KEY=.+$/m', "XCHACHA_KEY=$b64", $current);

    } else {
    //Append the key to the end of file
        $current .= PHP_EOL."XCHACHA_KEY=$b64";
    }
    file_put_contents($path, $current);
}
$this->info('Successfully generated new key for XChaCha');

Using preg_match() allows the original key to be retrieved as needed, also allows the key to be changed even if the actual value is not known.

1

Another option is using a config file instead of changing the content in the .env file.

Put all these in config files named like newfile.php inside the config folder, if you actually don't want to change .env content, and treat them as variable/array elements.

<?php

return [
    'PUSHER_APP_ID' => "",
    'PUSHER_APP_KEY' => "",
    'PUSHER_APP_SECRET' => "",
    'PUSHER_APP_CLUSTER' => "",
];

And get/set in controller like below:

config(['newfile.PUSHER_APP_ID' => 'app_id_value']); //set

config('newfile.PUSHER_APP_ID'); //get
1
  • and this config shouldn't be tracked by git therefore it should be in .gitignore Commented Jun 20, 2023 at 12:40
0

I had the same problem and have created the function below

public static function changeEnvironmentVariable($key,$value)
{
    $path = base_path('.env');

    if(is_bool(env($key)))
    {
        $old = env($key)? 'true' : 'false';
    }

    if (file_exists($path)) {
        file_put_contents($path, str_replace(
            "$key=".$old, "$key=".$value, file_get_contents($path)
        ));
    }
}
1
  • 1
    $old might be undefined
    – sgotre
    Commented Nov 23, 2017 at 12:49
0
public function setEnvironmentValue($key, $value) {
 $path = $_SERVER['DOCUMENT_ROOT'] . '/.env';

 if (file_exists($path)) {
   if (getenv($key)) {
     //replace variable if key exit
     file_put_contents($path, str_replace(
       "$key=" . getenv($key), "$key=" . $value, file_get_contents($path)
     ));
   } else {
     //set if variable key not exit
     $file   = file($path);
     $file[] = "$key=" . $value;
     file_put_contents($path, $file);
   }
 }
}
0

A simple way to update the .env key value in laravel is to add the below code in the controller function where you want to change .env values.

$key = 'VARIABLE_NAME';
$value = 'NEW VALUE';
file_put_contents(app()->environmentFilePath(), 
str_replace($key . '='. env($key),
$key . '=' . $value,file_get_contents(app()->environmentFilePath())));

The above lines of code will change the required key-value in the .env file. The next step is to clear the cache because the updated env value is not loaded; therefore, you need to reload configurations after successful change redirects to route with commands below.

Artisan::call('cache:clear');
Artisan::call('config:clear');
-1
   /**
     * Update Laravel Env file Key's Value
     * @param string $key
     * @param string $value
     */
    public static function envUpdate($key, $value)
    {
        $path = base_path('.env');

        if (file_exists($path)) {

            file_put_contents($path, str_replace(
                $key . '=' . env($key), $key . '=' . $value, file_get_contents($path)
            ));
        }
    }
-1
/**
 * @param string $key
 * @param string $val
 */
protected function writeNewEnvironmentFileWith(string $key, string $val)
{
    file_put_contents($this->laravel->environmentFilePath(), preg_replace(
        $this->keyReplacementPattern($key),
        $key . '=' . $val,
        file_get_contents($this->laravel->environmentFilePath())
    ));
}

/**
 * @param string $key
 * @return string
 */
protected function keyReplacementPattern(string $key): string
{
    $escaped = preg_quote('=' . env($key), '/');

    return "/^" . $key . "{$escaped}/m";
}
1
  • 1
    It's better to add explanation to the answer rather than code. Commented Jan 26, 2021 at 6:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.