karmendra
karmendra

Reputation: 2243

Updating config on runtime for a user

I am using Laravel 5.1

I created a function to get smtp info from db for a user $mail_config=STMPDetails::where('user_id',36)->first() and then I can just call config helper function and pass the array to set config value config($mail_config). and then I call Mail::queue function.

but before it reaches createSmtpDriver@vendor/laravel/framework/src/Illuminate/Mail/TransportManager.php where it reads the configuration again to send the mail, mail config are changed to the one specified in .env file.

Another thing to note is Mail sending function is in a Listener

I am not able to figure out where can I call the function such that configuration changes are retained before mail is sent.

Thanks, K

Upvotes: 3

Views: 3353

Answers (2)

alepeino
alepeino

Reputation: 9771

Since the default MailServiceProvider is a deferred provider, you should be able to change config details before the service is actually created.

Could you show the contents of $mail_config? I'm guessing that's the problem. It should be something like

config(['mail.port' => 587]);

Update - tested in 5.1 app:

Mail::queue('emails.hello', $data, function ($mail) use ($address) {
    $mail->to($address);
});

->> Sent normally to recipient.

config(['mail.driver' => 'log']);

Mail::queue('emails.hello', $data, function ($mail) use ($address) {
    $mail->to($address);
});   

->> Not sent; message logged.

Upvotes: 2

Nicolas Beauvais
Nicolas Beauvais

Reputation: 1052

This should work:

// Set your new config
Config::set('mail.driver', $driver);
Config::set('mail.from', ['address' => $address, 'name' => $name]);

// Re execute the MailServiceProvider that should use your new config
(new Illuminate\Mail\MailServiceProvider(app()))->register();

Upvotes: 4

Related Questions