最近我用资源实现了 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/