laravel change env dynamically code example
Example 1: laravel update env file dynamically
protected function updateDotEnv($key, $newValue, $delim='')
{
$path = base_path('.env');
$oldValue = env($key);
if ($oldValue === $newValue) {
return;
}
if (file_exists($path)) {
file_put_contents(
$path, str_replace(
$key.'='.$delim.$oldValue.$delim,
$key.'='.$delim.$newValue.$delim,
file_get_contents($path)
)
);
}
}
Example 2: update laravel .env variables dynamically
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)
));
}
}