Search code examples
phplaravelqueuejobs

Laravel switch between Queue and not Queue


how do you switch between ShouldQueue and Sync in a class?

We have got an endpoint which accepts an argument whether a job should be fired immediately or later.

In both cases the same logic should be executed but in one scenario I expect and answer back and the other one should be handled async.

I am aware of implementing "ShouldQueue" and use the "InteractsWithQueue"-Trait but how can we use this in one situation and not use it in the other?

Can you programatically set whether a request should be queued or not or are there better ways to do this? Thanks


Solution

  • In your controller:

    $this->dispatch($job) // queued if implements ShouldQueue
    
    $this->dispatchNow($job) // never queues
    

    If stuck on Laravel 5.1, create a new instance of the Dispatcher yourself:

    use Illuminate\Contracts\Bus\Dispatcher;
    
    // Later ...
    
    app(Dispatcher::class)->dispatchNow($job);