Laravel 8 - API、分页和资源。“链接” obj 到“元”键

vla*_*ani 5 api pagination laravel-8

我正在使用 Laravel 8 构建一个带有分页 JSON 的简单 API。

输出包含一个“链接”对象到“元”键:

{
  "data": [
    {
      . . .
    },
    {
      . . .
    }
  ],
  "links": {
    "prev": null,
    "first": "http://localhost/api/my-api?&page=1",
    "next": null,
    "last": "http://localhost/api/my-api?&page=2"
  },
  "meta": {
    "from": 1,
    "per_page": 400,
    "total": 477,
    "current_page": 1,
    "last_page": 2,
    "path": "http://localhost/api/my-api",
    "to": 400,
    "links": [
      {
        "url": null,
        "label": "Previous",
        "active": false
      },
      {
        "url": "http://localhost/api/my-api?&page=1",
        "label": 1,
        "active": true
      },
      {
        "url": "http://localhost/api/my-api?&page=2",
        "label": 2,
        "active": false
      },
      {
        "url": "http://localhost/api/my-api?&page=2",
        "label": "Next",
        "active": false
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我没有找到任何关于它的文档;此外,官方文档没有报告它:

如何删除“链接”对象?

Dim*_*rey 1

这有点诡计,因为我们不想触及源代码。在您的Http/Controller/Api/V1地图中或 API 集合类存在的任何位置,创建一个名为PaginateResourceResponseExtended.php. 将此代码添加到文件中:

\n
namespace App\\Http\\Controllers\\Api\\V1;\n\nuse Illuminate\\Support\\Arr;\nuse Illuminate\\Http\\Resources\\Json\\PaginatedResourceResponse;\n\nclass PaginateResourceResponseExtended extends PaginatedResourceResponse\n{\n    /**\n     * Gather the meta data for the response.\n     *\n     * @param  array  $paginated\n     * @return array\n     */\n    protected function meta($paginated)\n    {\n        return Arr::except($paginated, [\n            'data',\n            'first_page_url',\n            'last_page_url',\n            'prev_page_url',\n            'next_page_url',\n            'links' //<----- THIS!\n        ]);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

在您的资源集合类中,这是添加以下内容的扩展ResourceCollection:\nuse App\\Http\\Controllers\\Api\\V1\\PaginateResourceResponseExtended;

\n

在你的类中,你可以重写一个ResourceCollection名为的方法preparePaginatedResponse

\n
public function preparePaginatedResponse($request)\n{\n    if ($this->preserveAllQueryParameters) {\n        $this->resource->appends($request->query());\n    } elseif (! is_null($this->queryParameters)) {\n        $this->resource->appends($this->queryParameters);\n    }\n\n    return (new PaginateResourceResponseExtended($this))->toResponse($request);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

等瞧\xc3\xa0!

\n

当然,您也可以扩展该类Illuminate\\Http\\Resources\\Json\\ResourceCollection;,更改上述方法,并将其扩展到所有资源集合。

\n

meta中的受保护方法Illuminate\\Http\\Resources\\Json\\PaginatedResourceResponse是您想要通过简单地添加'links'到数组异常来更改的内容。

\n

只需祈祷您重写的 Laravel 源文件方法在下一个 Laravel 版本中不会改变

\n