Add some data in laravel paginate

Fan picture Fan · Dec 8, 2016 · Viewed 17.3k times · Source

As the tittle said, Here is my Controller

$book = Data::where('userId','1')->paginate(3);

return response()->json($book);

And get the json data like this:

data:[{id: 1, userId: 1, vendorId: 1, name: "Alfreda Berge PhD", phone: "1-850-813-5950 x96169",…},…]
from:1
last_page:2
next_page_url: "http:/localhost/XX/public/user/book/list/1?page=2"
perpage:4
prev_page_url:null
to:4
total:5
// if I want to add a new column and value here ,what should I do? 

I tried to do this :

$book = Data::where('userId','1')->paginate(3);
$book->printWord = 'Hellow!';
return response()->json($book);

But, It seem will remove the column printWord. Any idea?

Answer

Alexey Mezenin picture Alexey Mezenin · Dec 8, 2016

You can create collection with custom data manually and use merge() helper:

$book = Data::where('userId','1')->paginate(3);

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

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

return response()->json($data);

Just checked, it works just fine.