Dynamically change the .env file in Laravel
<?php
private function setEnv($key, $value)
{
file_put_contents(app()->environmentFilePath(), str_replace(
$key . '=' . env($value),
$key . '=' . $value,
file_get_contents(app()->environmentFilePath())
));
}
?>
There may be times when you want to dynamically change your .env
file on the fly. This could be an admin functionality or perhaps you are creating an install script and want to be able to dynamically update the database data in your .env file.
It's actually pretty simple, just use this function to pass in the $key, $value that you want to change and it will dynamically update your environment variables.
private function setEnv($key, $value)
{
file_put_contents(app()->environmentFilePath(), str_replace(
$key . '=' . env($value),
$key . '=' . $value,
file_get_contents(app()->environmentFilePath())
));
}
Hope this helps someone out.
Here is what the above code is doing:
1. It writes to the environment file, which is located in the root folder of your Laravel app
2. It replaces the key, which is the environment variable name, with the value
3. It replaces the value, which is the environment variable value, with the value