Dynamically change the .env file in Laravel 8

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. To do so you 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. Then, it will dynamically update your environment variables.

We need to make a function like this.

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

Source: https://devdojo.com/snippet/dynamically-change-env-file-in-laravel

Leave a Comment