在 laravel 分页中添加一些数据

2022-08-30 21:33:39

正如小花公所说,这是我的控制器

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

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

并获取如下所示的 json 数据:

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


答案 1

您可以使用自定义数据手动创建集合,并使用 merge() 帮助程序:

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

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

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

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

刚刚检查过,它工作得很好。


答案 2

如果“手动”使用 Illuminate\Pagination\LengthAwarePaginator 类,则可以选择扩展它并重写该方法:toArray

return new class(
    $collection,
    $count,
    $limit,
    $page,
    // https://github.com/laravel/framework/blob/6.x/src/Illuminate/Pagination/LengthAwarePaginator.php#L40
    // values here will become properties of the object
    [
        'seed' => $seed
    ]
) extends LengthAwarePaginator {
    public function toArray()
    {
        $data = parent::toArray();
        // place whatever you want to send here
        $data['seed'] = $this->seed;
        return $data;
    }
};

结果

current_page    1
data    []
first_page_url  "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
from    null
last_page   1
last_page_url   "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
next_page_url   null
path    "/finder"
per_page    20
prev_page_url   null
to  null
total   0
seed    0.2 // <-- our custom prop

实例化自己需要做一些额外的工作,但它可以完成工作。LengthAwarePaginator


推荐