Change the .env dynamically

Submitted by Fabs87 - 8 years ago

I was looking for a way to change the .env-values within a controller or from something else. I found nothing, so I created my own little method. It takes an array of new values. The array key must be the key from the .env. The script overwrites the old .env. Yet not perfect, but works for now. UPDATE: I am developing a package which will provide this functionality in a better way. The package will ship with some more features. UPDATE: Here is the Link to the Package: Give it a try ;) There will be more features in a few days.

class XyzController extends Controller {
     * Calls the method 
    public function something(){
        // some code
        $env_update = $this->changeEnv([
            'DB_DATABASE'   => 'new_db_name',
            'DB_USERNAME'   => 'new_db_user',
            'DB_HOST'       => 'new_db_host'
            // Do something
        } else {
            // Do something else
        // more code
    protected function changeEnv($data = array()){
        if(count($data) > 0){

            // Read .env-file
            $env = file_get_contents(base_path() . '/.env');

            // Split string on every " " and write into array
            $env = preg_split('/\s+/', $env);;

            // Loop through given data
            foreach((array)$data as $key => $value){

                // Loop through .env-data
                foreach($env as $env_key => $env_value){

                    // Turn the value into an array and stop after the first split
                    // So it's not possible to split e.g. the App-Key by accident
                    $entry = explode("=", $env_value, 2);

                    // Check, if new key fits the actual .env-key
                    if($entry[0] == $key){
                        // If yes, overwrite it with the new one
                        $env[$env_key] = $key . "=" . $value;
                    } else {
                        // If not, keep the old one
                        $env[$env_key] = $env_value;

            // Turn the array back to an String
            $env = implode("\n", $env);

            // And overwrite the .env with the new data
            file_put_contents(base_path() . '/.env', $env);
            return true;
        } else {
            return false;