Changing env values via controller in laravel

删除回忆录丶 提交于 2021-02-11 02:48:39

问题


Is there any ways that I could change my .env file values from controllers in laravel?

I've found this answer but it returns

Undefined property: App\Http\Controllers\Admin\PerformanceController::$laravel

code

$path = base_path('.env');
$key = false;

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

I want to have options in my admin panel to change debug mode between true or false, same as we have artisan commands in controller like Artisan::call('down') or Artisan::call('up') something like that.

Update

Now I have this code

$path = base_path('.env');
$key = 'true';

if (file_exists($path)) {
  file_put_contents($path, str_replace(
    'APP_DEBUG='.config('app.debug'), 'APP_DEBUG='.$key, file_get_contents($path)
  ));
}

this code does work but the issue is that it doesn't remove old value.

Before

APP_DEBUG=false

After

APP_DEBUG=truefalse
or
APP_DEBUG=falsefalse

any idea?


回答1:


it is not good idea to change your .env configuration. instead of that, use this code where you want change your APP_KEY.

be sure you did not cache your config

config(['app.key' => 'YOUR_NEW_KEY']);



回答2:


instead of using $this->laravel['config']['app.key'] try config('app.key')




回答3:


use this DotenvEditor::setKey('APP_KEY', 'new_value')->save();



来源:https://stackoverflow.com/questions/54340561/changing-env-values-via-controller-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!