gpt4 book ai didi

Laravel 资源分页元数据丢失

转载 作者:行者123 更新时间:2023-12-05 08:29:22 25 4
gpt4 key购买 nike

最近我用资源实现了 Laravel 分页。但问题是当我添加一些自定义属性或包装器时,分页元数据会丢失。没有包装器或自定义属性,工作正常。

资源类

class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}

Controller 函数

public function index()
{
return response()->json([
'success' => 'true',
'message'=>'Request successful',
'result' => UserResource::collection(User::paginate(3))
]);
}

输出

{
"success": "true",
"message": "Request successful",
"result": [
{
"id": 1,
"name": "System Admin",
"email": "admin@abc.com"
}
]
}

^ 缺少分页数据

期待

{
"success": "true",
"message": "Request successful",
"result": {
"data": [
{
"id": 1,
"name": "System Admin",
"email": "admin@abc.com"
},
{
......
}
],
"links": {
"first": "http://localhost:8080/api/v1/user?page=1",
"last": "http://localhost:8080/api/v1/user?page=4",
"prev": null,
"next": "http://localhost:8080/api/v1/user?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 4,
"path": "http://localhost:8080/api/v1/user",
"per_page": 3,
"to": 3,
"total": 11
}
}
}

谢谢。

最佳答案

我已经用

解决了这个问题
return response()->json([
'success' => 'true',
'message'=>'Request successful',
'result' => UserResource::collection(User::paginate(3))->response()->getData()
]);

关于Laravel 资源分页元数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71099881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com