How to set .env values in laravel programmatically

2019-01-18 00:03发布

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 controller once the user sets up and want to give user the flexibility to change them on the go using the GUI that I am making.

So my question is how do I write the values received from user to the .env file as an when I need from the controller.

And is it a good idea to build the .env file on the go or is there any other way around it?

Thanks in advance.

8条回答
Ridiculous、
2楼-- · 2019-01-18 00:49

Since Laravel uses config files to access and store .env data, you can set this data on the fly with config() method:

config(['database.connections.mysql.host' => '127.0.0.1']);

To get this data use config():

config('database.connections.mysql.host')

To set configuration values at runtime, pass an array to the config helper

https://laravel.com/docs/5.3/configuration#accessing-configuration-values

查看更多
神经病院院长
3楼-- · 2019-01-18 00:49

Replace signle 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)

查看更多
登录 后发表回答