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

前端 未结 14 983
忘掉有多难
忘掉有多难 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:48

    This solution builds upon the one provided by Elias Tutungi, it accepts multiple value changes and uses a Laravel Collection because foreach's are gross

        function set_environment_value($values = [])
        {
            $path = app()->environmentFilePath();
    
            collect($values)->map(function ($value, $key) use ($path) {
                $escaped = preg_quote('='.env($key), '/');
    
                file_put_contents($path, preg_replace(
                    "/^{$key}{$escaped}/m",
                   "{$key}={$value}",
                   file_get_contents($path)
                ));
            });
    
            return true;
        }
    

提交回复
热议问题