1

I have multiple databases and switching database as per some conditions before dispatching jobs. For eg:

if(condition A){
  DB::setDefaultConnection('A');
} else {
  DB::setDefaultConnection('B');
}
dispatch(new CreateNewUser($user))

And the db connection is changed as per the condition. As I query something like User::find($id) before dispatching the job which returns data as per the connected database. But the problem is, the dispatch() create a jobs record in jobs table of that database which was connected at first. When the db connection changed to another, still the first database's jobs table is populated. How is this happening?

1 Answer 1

0

Based on the comment, do the following, purge and reconnect after your change:

DB::purge('mysql'); 
//Do whatever you need to do to setup your connection
DB::setDefaultConnection('B');
DB::reconnect('mysql'); 

The job you are dispatching runs async. That DB change you are performing is not performed inside the Job. You should send the connection name as a parameter to the Job:

dispatch(new CreateNewUser($user, $connName))

and on the Job initialization, do:

    protected $connName;

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

    public function handle()
    {
        DB::setDefaultConnection($this->connName);
        ....
    }
Sign up to request clarification or add additional context in comments.

2 Comments

But I want to store the jobs to their particular database. That's why I'm changing default db-connection before dispatching jobs.
In that case: DB::purge('mysql'); Config::set('database.connections.mysql.database', 'A'); DB::reconnect('mysql');

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.