GodziLaravel's avatar

How to add custom attribute to pagination result

Hello ,

Here the code bellow :

$trainings->paginate($limit);

returns

{
  "current_page": 1,
  "data": [
   ...
  ],
  "first_page_url": "http://___________/api/trainings?xxxxx=xxxxx&page=1",
  "from": 1,
  "last_page": 1,
  "last_page_url": "http://___________/api/trainings?xxxxx=xxxxx&page=1",
  "next_page_url": null,
  "path": "http://___________/api/trainings",
  "per_page": 15,
  "prev_page_url": null,
  "to": 1,
  "total": 1
}

is it possible to add custom attribute : ("custom":"custom value") to that result ?

to have something like :

{
  "current_page": 1,

 "custom":"custom value", <------------ add this

  "data": [
   ...
  ],
  "first_page_url": "http://___________/api/trainings?xxxxx=xxxxx&page=1",
  "from": 1,
  "last_page": 1,
  "last_page_url": "http://___________/api/trainings?xxxxx=xxxxx&page=1",
  "next_page_url": null,
  "path": "http://___________/api/trainings",
  "per_page": 15,
  "prev_page_url": null,
  "to": 1,
  "total": 1
}

thanks

0 likes
2 replies
yoeriboven's avatar

$trainings->paginate($limit) returns a collection. You can then add your attribute to the collection and return it.

$trainings = $trainings->paginate($limit);

$trainings->put('custom_attribute', 'Custom Attribute');

return $trainings;
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Or something like this perhaps

$custom = collect(['custom' => 'My custom data here']);

$data = $custom->merge($trainings);

Please or to participate in this conversation.