如何在动态中以编程方式在Laravel中设置.env值

编程入门 行业动态 更新时间:2024-10-18 19:25:06
本文介绍了如何在动态中以编程方式在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值

本文发布于:2023-10-27 11:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533186.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中以   方式   动态   如何在   env

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!