How to paginate collection without keys Laravel

Viewed 292

I have an array of values with keys (like 0,1,2 etc). I need to paginate it and at result take collection of those values without keys.

At start I have array like this

array:11 [
  0 => {#829
    +"id": 2417
    +"date": "2019-12-24 15:05:04"
    +"eventName": "Atlas"
    +"gift_type": null
    +"count": 2
  }
  1 => {#872
    +"id": 2409
    +"date": "2019-08-22 19:00:00"
    +"eventName": "ДАХАБРАХА. ЗЕМЛЯ"
    +"gift_type": "to"
    +"count": 4
  }
]

And after pagination I need to get this, and I get it at first page :

{
    "current_page": 1,
    "data": [
        {
            "id": 2417,
            "date": "2019-12-24 15:05:04",
            "eventName": "Atlas",
            "gift_type": null,
            "count": 2
        },
        {
            "id": 2409,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 4
        }
    ],
    "first_page_url": "http://ticketsale/ajax/orders/77?page=1",
    "from": 1,
    "last_page": 4,
    "last_page_url": "http://ticketsale/ajax/orders/77?page=4",
    "next_page_url": "http://ticketsale/ajax/orders/77?page=2",
    "path": "http://ticketsale/ajax/orders/77",
    "per_page": 3,
    "prev_page_url": null,
    "to": 3,
    "total": 11
}

But at second page I take values WITH keys:

{
    "current_page": 2,
    "data": {
        "3": {
            "id": 2404,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 3
        },
        "4": {
            "id": 2400,
            "date": "2019-08-22 19:00:00",
            "eventName": "ДАХАБРАХА. ЗЕМЛЯ",
            "gift_type": "to",
            "count": 1
        }
    },
    "first_page_url": "http://ticketsale/ajax/orders/77?page=1",
    "from": 4,
    "last_page": 4,
1 Answers

I'm trying to fix it with the following.

public function paginate($items, $perPage, $page = null, $pageName = "page", $options = []) {
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);
    
    return new LengthAwarePaginator(array_values($items->forPage($page, $perPage)
        ->toArray()), $items->count(), $perPage, $page, $options);
}

And:

$result = (new CollectionUtil())->paginate($model_query, 5);
Related