jericopulvera's avatar

LengtAwarePaginator items

I have converted my collection to paginator but there is a slight difference.

This is my code to convert my collection into a paginator

  $page = $request->get('page', 1); // Get the ?page=1 from the url
        $perPage = 3; // Number of items per page

        $pagination = new LengthAwarePaginator(
            $ranked->forPage($page, $perPage), 
            count($ranked), // Total items
            $perPage, // Items per page
            $page, // Current page
            ['path' => $request->url(), 'query' => $request->query()] 
        );

return dd($pagination)

This is what I get when I dd it

    LengthAwarePaginator {#244 ▼
  #total: 50
  #lastPage: 17
  #items: Collection {#233 ▼
    #items: array:3 [▼
      0 => Post {#297 ▶}               // 0     index is the difference
      11 => Post {#308 ▶}            // 11  index is the difference
      10 => Post {#307 ▶}       // 10  index is the difference
    ]
  }
  #perPage: 3
  #currentPage: 1
  #path: "http://amafv-ecampus.dev/ajax/posts"
  #query: []
  #fragment: null
  #pageName: "page"
}

This is the return I get from the original paginator dd(Post::paginate(3))

LengthAwarePaginator {#289 ▼
  #total: 50
  #lastPage: 17
  #items: Collection {#288 ▼
    #items: array:3 [▼
      0 => Post {#287 ▶}  // 0
      1 => Post {#286 ▶}  // 1
      2 => Post {#285 ▶}  // 2
    ]
  }
  #perPage: 3
  #currentPage: 1
  #path: "http://amafv-ecampus.dev/ajax/posts"
  #query: []
  #fragment: null
  #pageName: "page"
}

Notice the difference. The original paginator's index is 0,1,2. while what I got is different.

What do you think is wrong with my code? I've been trying to fix this so I can properly retrieve the data from the response.

0 likes
2 replies
jericopulvera's avatar

How do I remove the index of this $ranked->forPage($page, $perPage)?

jericopulvera's avatar
jericopulvera
OP
Best Answer
Level 7

Finally found the solution

      $page = $request->get('page', 1); // Get the ?page=1 from the url
        $perPage = 3; // Number of items per page

        $pagination = new LengthAwarePaginator(
            $ranked->forPage($page, $perPage)->unique(), 
            count($ranked), // Total items
            $perPage, // Items per page
            $page, // Current page
            ['path' => $request->url(), 'query' => $request->query()] 
        );

return dd($pagination)

Please or to participate in this conversation.