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
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)
));
}
}