Add some data in laravel paginate

守給你的承諾、 提交于 2019-11-30 19:44:25

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.

The paginate function will return an object of the type Illuminate\Pagination\LengthAwarePaginator, it is not possible to just add another field to this.

I think the best solution for you would be to add the pagination object and the other values in an array and convert this array to json. This way your books data is seperated from the other data you want to add.

Like so:

return response()->json([
    'books' => $books,
    'foo' => 'bar'
]);

In this case your json object will look like this:

{
    books: {
        // Pagination object with books
    }
    foo: 'bar'
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!