Adding Data To Paginated Results

- 1 answer

Adding data after storing a query in a variable by using ->find($id) is pretty straight forward. I can use..

 $photo = Photo::with('likes')->find($id);
 $photo->total_likes = $photo->likes->count();

 return response()->json($photos, 200);

works like charm.. So I don't need to use a for loop

However, what if I want to add data to paginated results?

$photos = Photo::with('likes')->where('user_id', $user_id)->paginate(15);

return response()->json($photos, 200);

With that, the data I receive in return:

"total": 5,
"per_page": 15,
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 5,
"data": [
    "likes": [each like object..]

How can I use $photo->total_likes = $photo->likes->count(); approach to return total count after paginated result?



You can achieve this by creating a custom paginator instance. For example:

public function getNews() {
    $news = \App\News::select()->orderBy('created_at', 'desc')->get();

    $collection = $this->prepareNews($news);

    return $this->paginator($collection);

protected function prepareNews($news) {
    // do stuff with your news/whatever here
    foreach($news as $item) {
         'title' => $item->title,
         'category' => $item->category_id != 0 ? $categories[$item->category_id]['name'] : null,
    // Note the collect, this is important 
    return collect($arr);

protected function paginator(\Illuminate\Support\Collection $items, $perPage = 3) {
    //Get current page form url e.g. &page=6
    $currentPage = Paginator::resolveCurrentPage() - 1;
    $currentPageSearchResults = $items->slice($currentPage * $perPage, $perPage)->all();

    return new Paginator($currentPageSearchResults, count($items), $perPage);