PenAndPapers
PenAndPapers

Reputation: 2108

Laravel LengthAwarePaginator returned data are not in single obejct

So i have made a custom pagination in laravel 5.4 using

Illuminate\Pagination\LengthAwarePaginator;
\Illuminate\Pagination\Paginator;

it returns the correct data and format during first request, but the 2nd request and others are not formatted same way as the first one.

So my question is how do I make the data to always return in a single object like the first request?

Below is my code on how I did my custom paginator and the console log.

$data = collect($playerMatchArr);

$result = new LengthAwarePaginator(
    $data->forPage($page, 3), 
    $data->count(), 
    $limit, 
    $page
);

console result

Upvotes: 4

Views: 1747

Answers (3)

Umamad
Umamad

Reputation: 641

I found out that it's because keys of page 2 or more doesn’t start from 0 ( zero ) now can simply generate new collection or array which keys start from 0 ( zero ).

There is two ways for this:
Way one

array_values($data->forPage($page, 3));

Way two

collect([...$data->forPage($page, 3)]);

Overall you can fix it by refactor your code to this:

$data = collect($playerMatchArr);

$result = new LengthAwarePaginator(
    array_values($data->forPage($page, 3)), 
    $data->count(), 
    $limit, 
    $page
);

Upvotes: 2

$data = collect($playerMatchArr);
$dataPerPage = $data->forPage($page, 3);
$dataPerPage = array_values($dataPerPage->toArray());
$dataPerPage = Collection::make($dataPerPage);
$result = new LengthAwarePaginator(
    $dataPerPage,
    $data->count(),
    $limit,
    $page
);

Upvotes: 0

Abdul Qadir R.
Abdul Qadir R.

Reputation: 1201

It is laravel json response which is doing this. I also spent couple of hours on it

finally managed to convert the response on the front end by receiving the response as

Object.values(response.data.data)

And finally i got the results

enter image description here

Upvotes: 2

Related Questions