NameUnknown's avatar

No pagination data in a JsonResource when returning from a Job

This is unnecessary, but I'm just curious. I created a Job class and removed all Queue traits so it could be dispatched only synchronously. The only traits are:

class SyncJob{
	use Dispatchable, SerializesModels;

Not it can return data from handle() when I dispatch it via dispatchSync:

$models = SyncJob::dispatchSync();

The job returns models with pagination wrapped into a JsonResource collection:

public function handle()
{
			$models = SomeModel::paginate(20);
			return MyModelResrouce::collection($models);
}

But in this case, the collection has no pagination data.

If I do the same in a controller method, it works fine and contains all pagination data:

public function index()
{
			$models = SomeModel::paginate(20);
			return response()->json(MyModelResrouce::collection($models););
}

Obviously, it's due to use of a Job class. Is it possible to keep/add the pagination data when returning a resource collection from a Job class?

0 likes
3 replies
shariff's avatar

You can check this thread https://laracasts.com/discuss/channels/eloquent/paginate-not-working-while-returning-resource-collection-what-im-doing-wrong

example


$models = SomeModel::paginate(20);
return MyModelResrouce::collection($models)->response()->getData(true);

1 like
martinbean's avatar

@nameunknown It’s not “due to a job class”. It’s due to middleware which will transform the resource instance for presenting as JSON, which won’t happen in a job.

Why are you trying to use resources in a job in the first place?

You also don’t need to wrap resources in response()->json() in your controllers; Laravel will automatically convert it to a JSON response for you. So just return the resource from your controller directly.

NameUnknown's avatar

@martinbean You are right. I forgot about the response()->json() part.

Why are you trying to use resources in a job in the first place?

The model is subject to certain modifications after being loaded from DB. Resources do the trick, and the Job is needed to perform the same set of actions in different places

Please or to participate in this conversation.