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
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.