2

I'm returning JSON from LengthAwarePaginator but the JSON's data property is not an array. I need it to be an array. Any ideas?

// grab query parameters
$pageNumber = $request->input('page');
$pageSize = $request->input('pageSize');
// if query params do not exist call with defaults
if(!$pageNumber) {
  $pageNumber = 1;
}

if(!$pageSize) {
  $pageSize = 5;
}

$offset = ($pageNumber * $pageSize) - $pageSize;
// slice full array data based on page number and page size
$itemsForCurrentPage = array_slice($arrayOfData, $offset, $pageSize, true);
return new LengthAwarePaginator($itemsForCurrentPage, count($this->orgUsers), $pageSize, $pageNumber);

Returned data:

{
"total": 30,
"per_page": 5,
"current_page": 2,
"last_page": 6,
"next_page_url": "/?page=3",
"prev_page_url": "/?page=1",
"from": 6,
"to": 10,
"data": {
    "5": {
    "userId": "564110eadcb39832268ea873",
    "email": "[email protected]",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "6": {
    "userId": "564110ea2169bc358a3b65c2",
    "email": "[email protected]",
    "isActive": false,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "7": {
    "userId": "564110eaee662f30c4bd6772",
    "email": "[email protected]",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "8": {
    "userId": "dsdfgdfg",
    "email": "[email protected]",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg"
    },
    "9": {
    "userId": "564110eaf9526eb5ddd673a4",
    "email": "[email protected]",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg"
    }
}
}

TIA

2
  • just convert json to array using json_decode Commented Aug 2, 2016 at 5:31
  • 1
    in the array_slice change true to false Commented Dec 28, 2017 at 16:41

1 Answer 1

18

The problem is that the ids remain the keys of your array when array_slice-ing. But since some keys are missing, especially 0, 1, 2, … the array is henceforth treated as associative (['key1'=>'value1', 'key2'=>'value2', …]) rather than numerically indexed (['value1', 'value2', …]) when encoding to json.

The solution is to succeed your array_slice(…) with an array_values() call.

return new LengthAwarePaginator(array_values($itemsForCurrentPage), count($this->orgUsers), $pageSize, $pageNumber);

Edit: In case your $arrayOfData is an Eloquent/Illuminate Collection, you can use the methods ->slice($offset, $pageSize)->values() on it. Looks nicer!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.