Why laravel dispatcer dispatch() function not creating jobs in jobs table of particular database?

Viewed 44

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 Answers

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);
        ....
    }
Related