Laravel 资源分页元数据丢失

Nis*_*ara 3 laravel laravel-6

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

资源类

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

控制器功能

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

输出

{
    "success": "true",
    "message": "Request successful",
    "result": [
        {
            "id": 1,
            "name": "System Admin",
            "email": "admin@abc.com"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

^ 分页数据丢失

期待

{
  "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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

谢谢。

Nis*_*ara 12

我已经使用解决了这个问题

return response()->json([
       'success' => 'true',
       'message'=>'Request successful',
       'result' => UserResource::collection(User::paginate(3))->response()->getData()
      ]);
Run Code Online (Sandbox Code Playgroud)


kha*_*eeb 8

非常简单的解决方案

$data = UserResource::collection(User::paginate(3))->resource;
    
     return response()->json([
               'success' => 'true',
               'message'=>'Request successful',
               'data' => $data
              ]);enter code here
Run Code Online (Sandbox Code Playgroud)