Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 988
Chintan Palan Avatar asked Nov 06 '16 14:11

Chintan Palan


People also ask

How do I change environment variables in Laravel dynamically?

A simple way to update the . env key value in laravel is to add the below code in the controller function where you want to change . env values. $key = 'VARIABLE_NAME'; $value = 'NEW VALUE'; file_put_contents(app()->environmentFilePath(), str_replace($key .


1 Answers

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

config(['database.connections.mysql.host' => '127.0.0.1']); 

To get this data use config():

config('database.connections.mysql.host') 

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

https://laravel.com/docs/5.3/configuration#accessing-configuration-values

like image 188
Alexey Mezenin Avatar answered Oct 06 '22 01:10

Alexey Mezenin