Reputation: 1382
public function index(Request $request)
{
$params = $request->except('_token');
$profiles = Profile::filter($params);
$resultsSet = [
"result_count" => $profiles->count(),
"data" => $profiles->skip( ($params['page_number'] - 1) * $params['page_size'] )->take($params['page_size'])->get()
];
return json_encode($resultsSet);
}
This is working. However, as soon as I switch the order of the $resultSets
the resulting count()
value starts giving me 0 when the page_number is more than 1. Switched code for $resultsSet
is:
$resultsSet = [
"data" => $profiles->skip( ($params['page_number'] - 1) * $params['page_size'] )->take($params['page_size'])->get(),
"result_count" => $profiles->count()
];
Why is this happening? Thank you.
Upvotes: 0
Views: 563
Reputation: 3185
It is because the $profiles
data get manipulated after that skip
operation on it,
What you can do is to clone the variable and use it like this to make your count unaffected.
$profiles = Profile::filter($params);
$temp = clone $profiles // This is will make exact copy of your $profile variable
$resultsSet = [
"result_count" => $temp->count(),
"data" => $profiles->skip( ($params['page_number'] - 1) * $params['page_size'] )->take($params['page_size'])->get()
];
Now even if you reverse the order the count will remain unaffected
$resultsSet = [
"data" => $profiles->skip( ($params['page_number'] - 1) * $params['page_size'] )->take($params['page_size'])->get(),
"result_count" => $temp->count(),
];
I hope I explained it well.
Upvotes: 1