问题
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