PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Blocks

    Design blocks for your website

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

Dynamically change the .env file in Laravel

<?php

private function setEnv($key, $value)
{
	file_put_contents(app()->environmentFilePath(), str_replace(
		$key . '=' . env($value),
		$key . '=' . $value,
		file_get_contents(app()->environmentFilePath())
	));
}

?>

There may be times when you want to dynamically change your .env file on the fly. This could be an admin functionality or perhaps you are creating an install script and want to be able to dynamically update the database data in your .env file.

It's actually pretty simple, just use this function to pass in the $key, $value that you want to change and it will dynamically update your environment variables.

private function setEnv($key, $value)
{
	file_put_contents(app()->environmentFilePath(), str_replace(
		$key . '=' . env($value),
		$key . '=' . $value,
		file_get_contents(app()->environmentFilePath())
	));
}

Hope this helps someone out.

BETA Snippet explanation automatically generated by OpenAI:

Here is what the above code is doing:
1. It writes to the environment file, which is located in the root folder of your Laravel app
2. It replaces the key, which is the environment variable name, with the value
3. It replaces the value, which is the environment variable value, with the value

Snippet By Dev Dojo

ยท

Created June 12th, 2021

ยท

Report Snippet