Reputation: 12323
I am trying to return paginated results in an AJAX call. In my search i found Laravel 4.1 API Pagination - Create a custom JSON response
I tryed it but i cant fix it. The answer offers the following code:
$products = Product::paginate(100);
$response = [
'products' => $products->getItems()->toArray(),
'pagination' => [
'total' => $products->getTotal(),
'per_page' => $products->getPerPage(),
'current_page' => $products->getCurrentPage(),
'last_page' => $products->getLastPage(),
'from' => $products->getFrom(),
'to' => $products->getTo()
]
];
I changed it to
$myList = $myTable->paginate(10);
$response = array(
'products' => $myList->getItems()->toArray(),
'pagination' => array(
'total' => $myList->getTotal(),
'per_page' => $myList->getPerPage(),
'current_page' => $myList->getCurrentPage(),
'last_page' => $myList->getLastPage(),
'from' => $myList->getFrom(),
'to' => $myList->getTo()
)
);
but I get an error on $myList->getItems()->toArray()
Call to a member function toArray() on a non-object
i changed it to
$myList->toArray()
for testing purposes which returns
{"products":
{"total":2,"per_page":10,"current_page":1,"last_page":1,"from":1,"to":2,
"data":[{"id":41,"naam":"aqua 1","series_id":99,"stijlen_id":2,"kleuren_id":13,"datum":"2013-06-21 14:58:21","prijzen_id":1,"weergaven":21,"designers_id":0,"omschrijving":"geen omschrijving beschikbaar","video":"","img":"BetteAqua.jpg"},{"id":26,"naam":"one","series_id":100,"stijlen_id":2,"kleuren_id":13,"datum":"2013-06-21 13:40:09","prijzen_id":1,"weergaven":12,"designers_id":0,"omschrijving":"geen omschrijving beschikbaar","video":"","img":"BetteOne_2.png"}]},"pagination":{"total":2,"per_page":10,"current_page":1,"last_page":1,"from":1,"to":2}}
Here i found that the variable is called data so i tryed
$myList->data->toArray()
But that doesnt work either. How can i return the 'items' in the products array ?
edit:
The results are returned with :
return Response::json($response);
Upvotes: 0
Views: 4421
Reputation: 7371
The error occurs because getItems()
already returns an array
(see the source code).
To get just the data
, try:
'products' => $myList->toArray()['data']
Upvotes: 2