Laravel 资源分页元数据丢失

标签 laravel laravel-6

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

相关文章:

php - Laravel - 如何验证西里尔字母

laravel - 如何在没有用户模型的情况下使用策略?

mysql - 如何在 Laravel 中将数组中的元素存储到变量中?

php - Laravel 6.0 - 自定义电子邮件验证 : temporarySignedRoute() URL not working with new route

php - Laravel 中的项目从 5.8 更新到 6 时出现问题

php - 如何在 Laravel 6 中删除数据库?

php - Laravel:离线模式?

php - Laravel Blade 在没有 dd() 时显示错误,但可以使用它

php - 这个 MySQL 查询与 Laravel 查询生成器的等效项是什么?

javascript - 如何在使用 laravel 6 中导入自定义 javascript 和 css 文件