How to set .env values in laravel programmatically on the fly

More simplified:

public function putPermanentEnv($key, $value)
{
    $path = app()->environmentFilePath();

    $escaped = preg_quote('='.env($key), '/');

    file_put_contents($path, preg_replace(
        "/^{$key}{$escaped}/m",
        "{$key}={$value}",
        file_get_contents($path)
    ));
}

or as helper:

if ( ! function_exists('put_permanent_env'))
{
    function put_permanent_env($key, $value)
    {
        $path = app()->environmentFilePath();

        $escaped = preg_quote('='.env($key), '/');

        file_put_contents($path, preg_replace(
            "/^{$key}{$escaped}/m",
           "{$key}={$value}",
           file_get_contents($path)
        ));
    }
}

Watch out! Not all variables in the laravel .env are stored in the config environment. To overwrite real .env content use simply:

putenv ("CUSTOM_VARIABLE=hero");

To read as usual, env('CUSTOM_VARIABLE') or env('CUSTOM_VARIABLE', 'devault')

NOTE: Depending on which part of your app uses the env setting, you may need to set the variable early by placing it into your index.php or bootstrap.php file. Setting it in your app service provider may be too late for some packages/uses of the env settings.


Since Laravel uses config files to access and store .env data, you can set this data on the fly with config() method:

config(['database.connections.mysql.host' => '127.0.0.1']);

To get this data use config():

config('database.connections.mysql.host')

To set configuration values at runtime, pass an array to the config helper

https://laravel.com/docs/5.3/configuration#accessing-configuration-values