2
votes
  1. I need to modify the mail SMTP parameters such as MAIL_HOST and MAIL_USERNAME dynamically.

  2. For, this I am using Config::set() to set these values dynamically.

# This code works 
Config::set('mail.host', 'smtp.gmail.com');
Mail::to('[email protected]')->send(new myMailable());
  1. The above code works if I do not queue the mail.

  2. The moment I queue it, it appears that Config::set() fails to set the values.

Test to confirm Config::set() not working with queued jobs -

I created a simple job and put the below code in the handler.

public function handle()
{
    # set the config
    Config::set('mail.host', 'smtp.gmail.com');

    # confirm config has been set correctly
    logger('Setting host to = [' . config('mail.host') . ']');
}

The above code creates the below log entry.

Setting host to = []

Why can I not change the Config on-the-fly for queued jobs? And how to solve this?

1

1 Answers

1
votes

This is because the Queue worker doesn't use the current request. It is a stand-alone process, not being interferred by config settings.

To let this work, you need to use a Job. The dispatch function takes your data and sends it through to the job itself. From your controller, call:

JobName::dispatch($user, $settings);

In the job you set the variables accordingly:

public function __construct($user, $settings)
    {
        $this->user = $user;
        $this->settings = $settings;
}

Then in the handle method:

\Notification::sendNow($this->user, new Notification($this->settings));

You can use a normal notification for this. Do not for get to add implements ShouldQueue to your job!