1

How to dynamically set username and password(from database) in laravel (.env file) for sending mail using smtp

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=ssl
MAIL_FROM_NAME="${APP_NAME}"

i need to fill the username name and password from auth user mail and password.

5
  • Paste edit and add your controller code on your question, so I can give an answer Commented Nov 9, 2022 at 4:36
  • You cannot set it in the env file. But sure you can in the app/config/database.php. Commented Nov 9, 2022 at 4:50
  • You can create constants in config file for dynamic username and password Commented Nov 9, 2022 at 4:50
  • is there is any example for creating constants in config file for dynamic username and password for sending mails ? Commented Nov 9, 2022 at 5:01
  • Does this answer your question? Laravel dynamic config settings Commented Nov 9, 2022 at 5:03

1 Answer 1

-1

You can set dynamically set username and password(from database) in laravel (.env file).

$data = array('MAIL_USERNAME' => "set user name",'MAIL_PASSWORD' => "set password");

 if (count($data) > 0) {

            // Read .env-file
            $env = file_get_contents(base_path() . '/.env');

            // Split string on every " " and write into array
            $env = preg_split('/\s+/', $env);;

            // Loop through given data
            foreach ((array) $data as $key => $value) {

                // Loop through .env-data
                foreach ($env as $env_key => $env_value) {

                    // Turn the value into an array and stop after the first split
                    // So it's not possible to split e.g. the App-Key by accident
                    $entry = explode("=", $env_value, 2);

                    // Check, if new key fits the actual .env-key
                    if ($entry[0] == $key) {
                        // If yes, overwrite it with the new one
                        $env[$env_key] = $key . "=" . $value;
                    } else {
                        // If not, keep the old one
                        $env[$env_key] = $env_value;
                    }
                }
            }

            // Turn the array back to an String
            $env = implode("\n", $env);

            // And overwrite the .env with the new data
            file_put_contents(base_path() . '/.env', $env);

        \Artisan::call('config:cache');
        \Artisan::call('cache:clear');
        \Artisan::call('config:clear');
        \Artisan::call('optimize:clear');
        \Artisan::call('route:clear');

        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.