Skip to content
Advertisement

How to change php dotenv (.env) variables dynamically in laravel or php?

I want something like this:

env('APP_ENV');
setenv('APP_ENV', 'testing');
env('APP_ENV');

Output :

staging
testing

I find one answer How to change variables in the .env file dynamically in Laravel? but here .env is saved permanently, I don’t want to save permanently. How phpunit is doing this ? Because I can put in phpunit.xml this :

...
<php>
    <env name="APP_ENV" value="testing"/>
</php>
....

And env(‘APP_ENV’) gives me ‘testing’…

Advertisement

Answer

putenv() work like a charm :

echo env('APP_ENV');
putenv('APP_ENV=testing');
echo env('APP_ENV');

Output:

staging
testing

.env file is unattached …

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement