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

update_env($data);

 

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

 

Hope this Laravel set env variable tutorial will help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js
ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT