在 laravel paginate 中添加一些数据

2022-01-04 00:00:00 php laravel laravel-5 pagination

正如标题所说,这是我的控制器

As the tittle said, Here is my Controller

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

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

并像这样获取json数据:

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? 

我尝试这样做:

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

但是,它似乎会删除列printWord.有什么想法吗?

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

推荐答案

您可以手动创建包含自定义数据的集合并使用 merge() 助手:

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.

相关文章