动态合并 Laravel 5.7 中的 .env 文件旧键值

Dynamically merge .env file old key value in Laravel 5.7

我必须使用 file_put_content() 函数。但是当 .env 文件 $key 值为空时,它将添加新值,否则会显示错误。我需要合并旧值。

private function setEnv($key, $value)
{
    $path = base_path('.env');

        if (file_exists($path)) {

            file_put_contents($path, str_replace(
                $key . '=' . env($key),
                $key . '=' . $value,
                file_get_contents($path)
            ));
        }
}

你有什么想法吗?

每当您更改 .env 文件时,您需要通过 php artisan config:cache 刷新 Laravel 配置缓存。

所以你的函数将变成:

use Illuminate\Support\Facades\Artisan;

private function setEnv($key, $value)
{
    $path = base_path('.env');

    if (file_exists($path)) {

        // Get all the lines from that file
        $lines = explode("\n", file_get_contents($path));
        
        $settings = collect($lines)
            ->filter() // remove empty lines
            ->transform(function ($item) {
                return explode("=", $item, 2);
            }) // separate key and values
            ->pluck(1, 0); // keys to keys, values to values

        $settings[$key] = $value; // set the new value whether it exists or not

        $rebuilt = $settings->map(function ($value, $key) {
            return "$key=$value";
        })->implode("\n"); // rebuild the env file

        file_put_contents($path, $rebuilt); // put the new contents

        Artisan::call("config:cache"); // cache the added/modified parameter
    }
}