How To Update .env File In Laravel Programmatically

Hello artisan,

In this Laravel tutorial, I am going to explain laravel update env file programmatically step by step. I will show you a simple and easy way that how we can update the Laravel environment env variable dynamically.

You know that sometimes we need to update the environment env variable. So if you don't know the process of updating env variable then this tutorial is for you. See the example code of updating env variable dynamically.

Create a helper functions like that:

     * Update Env file
     * @param array $data

    if (!function_exists('update_env')) {
        function update_env( $data = [] ) : void

            $path = base_path('.env');

            if (file_exists($path)) {
                foreach ($data as $key => $value) {
                    file_put_contents($path, str_replace(
                        $key . '=' . env($key), $key . '=' . $value, file_get_contents($path)



And use it like below to update laravel env variable:

$data = [

  'APP_KEY' => 'deh23484'



Read also: Use Arr::get to Get Value From Deeply Nested Array in Laravel


Hope this Laravel set env variable tutorial will help you.


#laravel #laravel-tips