如何在动态中以编程方式在Laravel中设置.env值 [英] How to set .env values in laravel programmatically on the fly

查看:73
本文介绍了如何在动态中以编程方式在Laravel中设置.env值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义CMS,我正在Laravel中从头开始编写,并且想要在用户设置好并希望给用户灵活性后从控制器设置env值,即数据库详细信息,邮件详细信息,常规配置等.使用我制作的GUI随时随地更改它们.

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.

所以我的问题是,当需要控制器时,如何将从用户收到的值写入.env文件.

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.

在旅途中构建.env文件是个好主意吗?还是有其他解决方法?

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

提前谢谢.

推荐答案

基于totymedli的答案.

Based on totymedli's answer.

需要一次更改多个环境变量值的地方,可以传递一个数组(键->值).将添加以前不存在的任何密钥,并返回布尔值,以便您可以测试成功.

Where it is required to change multiple enviroment variable values at once, you could pass an array (key->value). Any key not present previously will be added and a bool is returned so you can test for success.

public function setEnvironmentValue(array $values)
{

    $envFile = app()->environmentFilePath();
    $str = file_get_contents($envFile);

    if (count($values) > 0) {
        foreach ($values as $envKey => $envValue) {

            $str .= "\n"; // In case the searched variable is in the last line without \n
            $keyPosition = strpos($str, "{$envKey}=");
            $endOfLinePosition = strpos($str, "\n", $keyPosition);
            $oldLine = substr($str, $keyPosition, $endOfLinePosition - $keyPosition);

            // If key does not exist, add it
            if (!$keyPosition || !$endOfLinePosition || !$oldLine) {
                $str .= "{$envKey}={$envValue}\n";
            } else {
                $str = str_replace($oldLine, "{$envKey}={$envValue}", $str);
            }

        }
    }

    $str = substr($str, 0, -1);
    if (!file_put_contents($envFile, $str)) return false;
    return true;

}

这篇关于如何在动态中以编程方式在Laravel中设置.env值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆