mushu8's avatar

Optimisation of Pagination for api

Hi, i'm developing an api with Laravel and DingoAPI which returns the message threads of the user with pagination.

$threads = Thread::forUser($currentUserId)->latest('updated_at')
        ->simplePaginate(1);
        return API::response()->array($threads);

and i get this kind of response :

{
  "per_page": 1,
  "current_page": 1,
  "next_page_url": "http://my.app/api/messages?page=2",
  "prev_page_url": null,
  "from": 1,
  "to": 1,
  "data": [
    {
      "id": 1,
      "subject": null,
      "created_at": "2016-03-18 12:33:38",
      "updated_at": "2016-03-18 12:33:38",
      "deleted_at": null
    }
  ]
}

What can i do to remove some field of the response ? i just need data and next_page_url …

0 likes
8 replies
andremellow's avatar
Level 9

use unset in your array before return or create a new array

unset($threads['per_page'] );
unset($threads['current_page'] );
unset($threads['prev_page_url'] );
unset($threads['from'] );
unset($threads['to'] );

return API::response()->array($threads);

or

$array = [
    'next_page_url' => $threads['next_page_url'],
    'data' => $threads['data']
]

return API::response()->array($array);

:)

1 like
mushu8's avatar

@andremellow sorry actually it doens't work.

only null values are returned in the $array.

I guess Dingo Api is doing some work behind the scene…

mushu8's avatar

@andremellow your solution :

$array = [
    'next_page_url' => $threads['next_page_url'],
    'data' => $threads['data']
]

return API::response()->array($array);

but every keys have null values

andremellow's avatar

first all try a dd ($array);

$array = [
    'next_page_url' => $threads['next_page_url'],
    'data' => $threads['data']
]
 dd ($array);

return API::response()->array($array);

if your array have data, try to return like this:

return json_enconde($array);
mushu8's avatar

i did it !!

it returns :

<pre class='xdebug-var-dump' dir='ltr'>
<small>/home/vagrant/love_wangu/app/Api/V1/Http/Controllers/MessagesController.php:54:</small>
<b>array</b> <i>(size=2)</i>
  'next_page_url' <font color='#888a85'>=&gt;</font> <font color='#3465a4'>null</font>
  'data' <font color='#888a85'>=&gt;</font> <font color='#3465a4'>null</font>
</pre>
andremellow's avatar

by the way I prefere returning a json

return Response::json($array , 200);
andremellow's avatar

can you place all your function code here?

and try dd( $threads ) as well;

Please or to participate in this conversation.