How to set .env values in laravel programmatically on the fly

前端 未结 14 1015
忘掉有多难
忘掉有多难 2020-12-01 09:05

I have a custom CMS that I am writing from scratch in Laravel and want to set env values i.e. database details, mailer details, general configuration, etc from

14条回答
  •  情书的邮戳
    2020-12-01 09:45

    You can use this custom method i located from internet ,

      /**
     * 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'
        ]);
        if($env_update){
            // 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;
            }
        }
    

提交回复
热议问题