How to update Laravel .env variables dynamically?

To develop a web application we need to work with different environment variables. These can be added in the .env file. Default of the .env file contains some common configuration values. These may differ based on whether your application runs on a production server or locally. There are many ways to change the variables in the .env file. Let’s see how to update Laravel .env variables dynamically. 

At times you might need to dynamically change your .env variables. This could be to edit an admin functionality or when you are creating an install script and want to be able to dynamically update the database data in your .env file.

This can be useful when you need to edit an admin function or create an install script that you can use to dynamically update database information present in your .env file.

The process is pretty simple, just use the function below and pass in the $key, $value that you want to change and it dynamically updates your environment variables.

private function setNewEnv($key, $value)
	file_put_contents(app()->environmentFilePath(), str_replace(
		$key . '=' . env($value),
		$key . '=' . $value,

The process is straight forward. It sets the $key from the .env file to an updated $value. We call the String replace function on it. We can pass any value to the $key and $value variables along with the function.

For example, if we need to update database name in the .env file from user to admin. We may call the function as below.

setNewEnv("DATABASE_NAME", "admin")

Here, we read the variable “DATABASE_NAME” from the .env file. The function code is applied on it which replaced its value from user to admin. You can specify the new value in the $value variable.