โดยปกติแล้ว เราสามารถใส่ชื่อตัวแปรและค่าของตัวแปรนั้นๆเข้าไปในไฟล์ .env ได้เลย
แต่ในบางกรณี เราไม่สามารถกำหนดค่าของตัวแปรนั้นได้ เช่น ค่าที่ต้อง encrypt ผ่าน Application หรือค่าของตัวแปรนั้นสามารถหาได้ในขณะ Runtime เท่านั้น เช่น IP address ของ Host server เป็นต้น
สมมติว่า
- $key เก็บชื่อตัวแปรที่เราต้องการเพิ่มหรือแก้ไข
- $newValue เป็นค่าใหม่ของตัวแปรข้างต้น
private function updateEnv($key, $newValue)
{
$path = base_path('.env');
if (!file_exists($path)) {
touch($path);
}
$oldValue = env($key);
if (isset($oldValue)) {
file_put_contents($path, str_replace(
"$key=$oldValue",
"$key=$newValue",
file_get_contents($path)
));
} else {
file_put_contents($path, file_get_contents($path) . "\n$key=$newValue");
}
}
No comments:
Post a Comment