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

前端 未结 14 1017
忘掉有多难
忘掉有多难 2020-12-01 09:05

I have a custom CMS that I am writing from scratch in Laravel and want to set env values i.e. database details, mailer details, general configuration, etc from

14条回答
  •  囚心锁ツ
    2020-12-01 09:54

    In the event that you want these settings to be persisted to the environment file so they be loaded again later (even if the configuration is cached), you can use a function like this. I'll put the security caveat in there, that calls to a method like this should be gaurded tightly and user input should be sanitized properly.

    private function setEnvironmentValue($environmentName, $configKey, $newValue) {
        file_put_contents(App::environmentFilePath(), str_replace(
            $environmentName . '=' . Config::get($configKey),
            $environmentName . '=' . $newValue,
            file_get_contents(App::environmentFilePath())
        ));
    
        Config::set($configKey, $newValue);
    
        // Reload the cached config       
        if (file_exists(App::getCachedConfigPath())) {
            Artisan::call("config:cache");
        }
    }
    

    An example of it's use would be;

    $this->setEnvironmentValue('APP_LOG_LEVEL', 'app.log_level', 'debug');
    

    $environmentName is the key in the environment file (example.. APP_LOG_LEVEL)

    $configKey is the key used to access the configuration at runtime (example.. app.log_level (tinker config('app.log_level')).

    $newValue is of course the new value you wish to persist.

提交回复
热议问题