mafortis
mafortis

Reputation: 7128

Changing env values via controller in laravel

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?

Upvotes: 2

Views: 9074

Answers (3)

george many
george many

Reputation: 39

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

Upvotes: 0

Mehdi Meshkatian
Mehdi Meshkatian

Reputation: 308

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

Upvotes: 0

Mehrdad Mahdian
Mehrdad Mahdian

Reputation: 119

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']);

Upvotes: 2

Related Questions