Laravel 5.4 pagination with relationship

Viewed 260

I have two tables questions and answers. Question table has relationship on answer table.

When paginating eloquent results on the first page it returns lets say 7 unanswered questions (with empty relationship) and 3 with answered questions, but I need it to return 5 with answers and 5 without answers in total 10.

Right now i'm doing this:

Question::with(['user', 'answers])->paginate(10);

Is there any way to return always 5 answered/5 unanswered instead of random?

1 Answers

The paginate() method returns a LengthAwarePaginator object so you can create your own as the doc suggests. Maybe (I haven't tested it) you can do it more or less like this:

$limit = $request->input('limit', 5);
$page = $request->input('page', 1);
$total = Question::count();
$offset = ($page - 1) * $limit;

$items1 = Question::with(['user', 'answers'])->has('answers')->limit($limit)->offset($offset)->get();
$items2 = Question::with(['user', 'answers'])->doesntHave('answers')->limit($limit)->offset($offset)->get();

$paginator = new \Illuminate\Pagination\LengthAwarePaginator(
    $items1->concat(items2),
    $total,
    $limit,
    $page,
    ['path' => $request->getPathInfo()]
);

return response()->json($paginator); 
Related