Update .env value via Laravel

2019-08-02 15:56发布

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

3条回答
别忘想泡老子
2楼-- · 2019-08-02 16:36

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');
查看更多
Luminary・发光体
3楼-- · 2019-08-02 16:39

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

查看更多
混吃等死
4楼-- · 2019-08-02 16:51

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.

查看更多
登录 后发表回答