Home  >  Article  >  Backend Development  >  Detailed explanation of how Laravel modifies .env configuration through the background

Detailed explanation of how Laravel modifies .env configuration through the background

*文
*文Original
2018-01-02 17:31:461955browse

How does Laravel modify .env configuration through the background? When using the laravel framework to develop PHP programs, it is crucial to configure the .env file of the framework. This file needs to configure the database, database user, cache, etc. The following article mainly introduces you to the relevant information on how Laravel can modify the .env configuration file in a friendly way. Friends in need can refer to it. I hope to be helpful.

Preface

Do I have to modify the code every time I change .env? Can the .env file be configured in the background? In fact, it is very simple to implement. Add the following functions to your project

Sample code

function modifyEnv(array $data) 
{
 $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';

 $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));

 $contentArray->transform(function ($item) use ($data){
   foreach ($data as $key => $value){
    if(str_contains($item, $key)){
     return $key . '=' . $value;
    }
   }

   return $item;
  });

 $content = implode($contentArray->toArray(), "\n");

 \File::put($envPath, $content);
}

Use

// 你可以更新你想要的任何值 key => value 
$data = [
 'APP_ENV' => 'your_environment',
 'APP_KEY' => 'your_key',
 'APP_DEBUG' => 'trueOrFalse',
 'DB_DATABASE' => 'test',
 'DB_USERNAME' => 'test',
 'DB_PASSWORD' => 'test',
 'DB_HOST' => 'localhost',
 'CACHE_DRIVER' => 'file',
 'SESSION_DRIVER' => 'file',
];

// 或者
$data = [
 'DB_HOST' => '127.0.0.1',
];

// 使用函数更新
modifyEnv($data);

How about it? Isn’t it very simple? Then you can configure Laravel’s .env file graphically through the background~

Related recommendations:

#How to migrate data and fill data in Laravel?

How to use the corresponding interface of Laravel 5.5?

laravel writing APP interface (API)

The above is the detailed content of Detailed explanation of how Laravel modifies .env configuration through the background. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn