Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change variables in the .env file dynamically in Laravel?

Tags:

I want to create a Laravel web app that allows an admin user to change some variables(such as database credentials) in the .env file using the web backend system. But how do I save the changes?

like image 791
Joshua Leung Avatar asked Aug 31 '15 08:08

Joshua Leung


People also ask

Is .env a config file?

In case you are still wondering what all this means, well, you are probably new to the . env file. It's actually a simple configuration text file that is used to define some variables you want to pass into your application's environment. This file needs a something like a parser to make it work.


2 Answers

There is no built in way to do that. If you really want to change the contents of the .env file, you'll have to use some kind of string replace in combination with PHP's file writing methods. For some inspiration, you should take a look at the key:generate command: KeyGenerateCommand.php:

$path = base_path('.env');  if (file_exists($path)) {     file_put_contents($path, str_replace(         'APP_KEY='.$this->laravel['config']['app.key'], 'APP_KEY='.$key, file_get_contents($path)     )); } 

After the file path is built and the existence is checked, the command simply replaces APP_KEY=[current app key] with APP_KEY=[new app key]. You should be able to do the same string replacement with other variables.
Last but not least I just wanted to say that it might isn't the best idea to let users change the .env file. For most custom settings I would recommend storing them in the database, however this is obviously a problem if the setting itself is necessary to connect to the database.

like image 117
lukasgeiter Avatar answered Oct 01 '22 02:10

lukasgeiter


Yet another implementation, in case you have something like:

A = B #this is a valid entry

In your .env file

public function updateEnv($data = array()) {     if (!count($data)) {         return;     }      $pattern = '/([^\=]*)\=[^\n]*/';      $envFile = base_path() . '/.env';     $lines = file($envFile);     $newLines = [];     foreach ($lines as $line) {         preg_match($pattern, $line, $matches);          if (!count($matches)) {             $newLines[] = $line;             continue;         }          if (!key_exists(trim($matches[1]), $data)) {             $newLines[] = $line;             continue;         }          $line = trim($matches[1]) . "={$data[trim($matches[1])]}\n";         $newLines[] = $line;     }      $newContent = implode('', $newLines);     file_put_contents($envFile, $newContent); } 
like image 37
Daniel Teleginski Camargo Avatar answered Oct 01 '22 01:10

Daniel Teleginski Camargo