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

前端 未结 7 959
无人共我
无人共我 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:46

    I had the same problem and have created the function below

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

提交回复
热议问题