vendredi 28 septembre 2018

How to add custom properties to Laravel paginate json response

I have the following simple index method:

public function index()
    {
       // dd(Poll::paginate(2));
      return response()->json(Poll::paginate(2),200);
    }

The output of that method is looks like the following json object:

{
"current_page": 1,
"data": [
{
"id": 1,
"title": "I suppose?' said Alice. 'Why, you don't know.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
},
{
"id": 2,
"title": "Alice; but she knew that it seemed quite.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
}
],
"first_page_url": "http://127.0.0.1:8000/polls?page=1",
"from": 1,
"last_page": 6,
"last_page_url": "http://127.0.0.1:8000/polls?page=6",
"next_page_url": "http://127.0.0.1:8000/polls?page=2",
"path": "http://127.0.0.1:8000/polls",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 11
}

I want to add another array property after "total: 11" attribute such as:

,
"anotherData" : [
   "userId": 1,
   "userName": "john10",
   "message": "This is a message"
]

I have tried to understand how response()->json() works, so it can extract some data from LengthAwarePaginator object which it is the output of Poll::paginate(2) from this resource, but I could not able to understand how does it able to get an array from LengthAwarePaginator that holds the resultant keys in the json object?!

Edit

Notice: I have found the answer.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire