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

前端 未结 14 1014
忘掉有多难
忘掉有多难 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:52

    Replace single value in .env file function:

    /**
     * @param string $key
     * @param string $value
     * @param null $env_path
     */
    function set_env(string $key, string $value, $env_path = null)
    {
        $value = preg_replace('/\s+/', '', $value); //replace special ch
        $key = strtoupper($key); //force upper for security
        $env = file_get_contents(isset($env_path) ? $env_path : base_path('.env')); //fet .env file
        $env = str_replace("$key=" . env($key), "$key=" . $value, $env); //replace value
        /** Save file eith new content */
        $env = file_put_contents(isset($env_path) ? $env_path : base_path('.env'), $env);
    }
    

    Example to local (laravel) use: set_env('APP_VERSION', 1.8).

    Example to use custom path: set_env('APP_VERSION', 1.8, $envfilepath).

提交回复
热议问题