Chintan Palan Chintan Palan - 5 months ago 54
PHP Question

How to set .env values in laravel programmatically on the fly

I have a custom CMS that I am writing from scratch in Laravel and want to set env values ie. 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. 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.
And is it a good idea to build the .env file on the go or is there any other way around it?
Thanks in advance.


Since Laravel uses config files to access and store .env data, you can set this data on the fly with config() method:

config(['' => '']);

To get this data use config():


To set configuration values at runtime, pass an array to the config helper