Return data from Laravel Jobs

前端 未结 1 2006
后悔当初
后悔当初 2021-02-14 13:36

I am developing API on Laravel for mobile application.

Methods will make requests to other API\'s, combine and filter data, changing it\'s stru

1条回答
  •  独厮守ぢ
    2021-02-14 14:15

    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 :)

    0 讨论(0)
提交回复
热议问题