Return data from Laravel Jobs Return data from Laravel Jobs php php

Return data from Laravel Jobs


You are returning data in your Job class, but assigning $data to a dispatcher - note that dispatch() method is not a part of your Job class.

You could try something like this, assuming that your jobs run synchronously:

private $apiActionName;private $response;public function __construct($apiActionName){    $this->apiActionName = $apiActionName;}public function handle(SomeService $someService){    $this->response = $someService->{$this->apiActionName}();}public function getResponse(){    return $this->response;}

And then in your controller:

public function someAction(){     $job = new MyJob($apiActionName);    $data = $this->dispatch($job);    return response()->json($job->getResponse());}

Obviously, this won't work once you move to async mode and queues - response won't be there yet by the time you call getResponse(). But that's the whole purpose of async jobs :)


If you want return data from Laravel jobs, you need write some Queue methods at Providers/AppServiceProvider.php inside boot method (Laravel 7.x / 8)

public function boot(){   Queue::before(function ( JobProcessing $event ) {      Log::info('Job ready: ' . $event->job->resolveName());      Log::info('Job started: ' . $event->job->resolveName());   });       Queue::after(function ( JobProcessed $event ) {      Log::notice('Job done: ' . $event->job->resolveName());      Log::notice('Job payload: ' . print_r($event->job->payload(), true));   });       Queue::failing(function ( JobFailed $event ) {       Log::error('Job failed: ' .                   $event->job->resolveName() .                  '(' . $event->exception->getMessage() . ')'                 );   });}