laravellaravel-5.8laravel-queue

Running Laravel job chain synchronously


I have a Laravel job chain like this

Job1::withChain([
  new Job2(),
  new Job3(),
  new Job4()
])->dispatch();

Sometimes I want it to run the job synchronously.

But when I change ->dispatch() to ->dispatchNow(), I get

Call to undefined method Illuminate\Foundation\Bus\PendingChain::dispatchNow()

Is there any other way to run a job chain synchronously?


Solution

  • You can use the allOnConnection method and run them on the sync connection:

    Job1::withChain([
      new Job2(),
      new Job3(),
      new Job4()
    ])->dispatch()->allOnConnection('sync');
    

    Just check that the driver for the sync connection in your config/queue.php file is indeed 'sync'.

    Another option, which is not ideal for when you want to easily "toggle" between running the jobs synchronously vs asynchronously, is to just dispatch them one after the other, e.g.:

    Job1::dispatchNow();
    Job2::dispatchNow();
    Job3::dispatchNow();
    Job4::dispatchNow();