code-8
code-8

Reputation: 58632

Update .env value via Laravel

Example, if my .env is

APP_ENV=local
APP_URL=http://localhost:8888/
APP_DEBUG=true
FACEBOOK_APP_ID = ABC

I know in Laravel we can do access our .env file by doing this

echo env('APP_ENV'); --> 'local'
echo env('APP_URL'); --> 'http://localhost:8888/'

but I wonder if there is a way to programmatically set it

Ex. env('APP_ENV') == 'production';

Upvotes: 4

Views: 14258

Answers (4)

Syamsoul Azrien
Syamsoul Azrien

Reputation: 2742

You can easily update or insert the variable in .env file by using syamsoul/laravel-set-env package.

.

  1. Install via composer
composer require syamsoul/laravel-set-env

.

  1. Just run this code
use SoulDoit\SetEnv\Env;

$envService = new Env(); 
$envService->set("MY_APP_NAME", "My Laravel Application");

.

  1. Or, run artisan command
php artisan souldoit:set-env
  • You will be prompted about the variable name and the value.

.

  1. Or, same artisan command, but just straightaway put the variable name and value into the argument.
php artisan souldoit:set-env "APP_NAME=My New Laravel Name"

. .

P/S: Tested on Laravel 10 and above and it is working fine.

For more info: https://github.com/syamsoul/laravel-set-env

Upvotes: 1

Saiful Islam
Saiful Islam

Reputation: 670

This might help.

function setEnv($name, $value)
{
    $path = base_path('.env');
    if (file_exists($path)) {
        file_put_contents($path, str_replace(
            $name . '=' . env($name), $name . '=' . $value, file_get_contents($path)
        ));
    }
}
setEnv('APP_ENV','abc');

Upvotes: 13

apokryfos
apokryfos

Reputation: 40653

You can use:

putenv("APP_ENV=production");

because env is just a convenience wrapper around getenv which does some type conversion.

Note: this is not permanent as it will be overwritten by .env when the next request happens.

Upvotes: 1

ATechGuy
ATechGuy

Reputation: 1270

try this

$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)
));
}

taken from here stack answer

Upvotes: 2

Related Questions