How to change variables in the .env file dynamically in Laravel?

前端 未结 7 945
无人共我
无人共我 2020-11-28 08:16

I want to create a Laravel web app that allows an admin user to change some variables(such as database credentials) in the .env file using the web backend system. But how do

7条回答
  •  一整个雨季
    2020-11-28 08:45

    Update Erick's answer with consideration of $old values covering sting, bool and null values.

    public static function changeEnvironmentVariable($key,$value)
    {
        $path = base_path('.env');
    
        if(is_bool(env($key)))
        {
            $old = env($key)? 'true' : 'false';
        }
        elseif(env($key)===null){
            $old = 'null';
        }
        else{
            $old = env($key);
        }
    
        if (file_exists($path)) {
            file_put_contents($path, str_replace(
                "$key=".$old, "$key=".$value, file_get_contents($path)
            ));
        }
    }
    

提交回复
热议问题