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.
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.
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.
Watch out! Not all variables in the laravel .env are stored in the config environment. To overwrite real .env content use simply:
putenv ("CUSTOM_VARIABLE=hero");
To read as usual, env('CUSTOM_VARIABLE') or env('CUSTOM_VARIABLE', 'devault')
tl;dr
Based on vesperknight's answer I created a solution that doesn't use
strtok
orenv()
.Explanation
This doesn't use
strtok
that might not work for some people, orenv()
that won't work with double-quoted.env
variables which are evaluated and also interpolates embedded variablesMore simplified:
or as helper:
Based on josh's answer. I needed a way to replace the value of a key inside the
.env
file.But unlike josh's answer, I did not want to depend on knowing the current value or the current value being accessible in a config file at all.
Since my goal is to replace values that are used by Laravel Envoy which doesn't use a config file at all but instead uses the
.env
file directly.Here's my take on it:
Usage:
In the event that you want these settings to be persisted to the environment file so they be loaded again later (even if the configuration is cached), you can use a function like this. I'll put the security caveat in there, that calls to a method like this should be gaurded tightly and user input should be sanitized properly.
An example of it's use would be;
$environmentName
is the key in the environment file (example.. APP_LOG_LEVEL)$configKey
is the key used to access the configuration at runtime (example.. app.log_level (tinkerconfig('app.log_level')
).$newValue
is of course the new value you wish to persist.