Laravel 5.6: Customise a paginated resource collection meta and links attributes

Den*_*310 1 php laravel eloquent laravel-5.6 laravel-resource

How can I customize Laravel ResourceCollection meta and links information.

Links should include only prev,next and self instead of first,last,prev,next that is by default.

Meta should include pagination iformation like: current_page, total_items, items_per_page, total_pages instead of current_page, from, last_page, path, per_page, to, total.

This is how meta and links information looks now in JSON response:

"meta": {
    "currentPage": 2,
    "current_page": 1,
    "from": 1,
    "last_page": 3,
    "path": "http://localhost:8000/api",
    "per_page": 5,
    "to": 5,
    "total": 14
},
"links": {
    "self": "http://localhost:8000/api",
    "first": "http://localhost:8000/api?page=1",
    "last": "http://localhost:8000/api?page=3",
    "prev": null,
    "next": "http://localhost:8000/api?page=2"
}
Run Code Online (Sandbox Code Playgroud)

.. I want it to be something like:

"meta": {
    "current_page": 1,
    "total_items": 15,
    "per_page": 5,
    "total_pages": 3
},
"links": {
    "prev": null,
    "next": "http://localhost:8000/api?page=2"
    "self": "http://localhost:8000/api",
}
Run Code Online (Sandbox Code Playgroud)

Yah*_*din 6

我不喜欢 Laravel 如何实现分页器和资源,因为它很难做某些事情,比如你提到的问题。

内件

在以您想要的方式自定义您的响应之前,您首先需要了解 ResourceCollections 如何转换为响应。

toResponse资源集合的原始方法如下所示:

public function toResponse($request)
{
    return $this->resource instanceof AbstractPaginator
                ? (new PaginatedResourceResponse($this))->toResponse($request)
                : parent::toResponse($request);
}
Run Code Online (Sandbox Code Playgroud)

如果您进一步PaginatedResourceResponse查看类,您将看到以下代码。

...
protected function paginationLinks($paginated)
{
    return [
        'first' => $paginated['first_page_url'] ?? null,
        'last' => $paginated['last_page_url'] ?? null,
        'prev' => $paginated['prev_page_url'] ?? null,
        'next' => $paginated['next_page_url'] ?? null,
    ];
}
...

protected function meta($paginated)
{
    return Arr::except($paginated, [
        'data', 
        'first_page_url',
        'last_page_url',
        'prev_page_url',
        'next_page_url',
    ]);
}
Run Code Online (Sandbox Code Playgroud)

我建议阅读Illuminate\Http\Resources\Json\PaginatedResourceResponseIlluminate\Http\Resources\Json\ResourceResponse充分了解正在发生的事情。

解决方案 1:创建自定义的 PaginatedResourceResponse

一种解决方案是创建一个扩展的新类PaginatedResourceResponse,并覆盖该paginationLinks方法。

所以它看起来像:

use Illuminate\Http\Resources\Json\PaginatedResourceResponse;

class CustomPaginatedResourceResponse extends PaginatedResourceResponse
{
    protected function paginationLinks($paginated)
    {
        return [
            'prev' => $paginated['prev_page_url'] ?? null,
            'next' => $paginated['next_page_url'] ?? null,
        ];
    }

    protected function meta($paginated)
    {
        $metaData = parent::meta($paginated);
        return [
            'current_page' => $metaData['current_page'] ?? null,
            'total_items' => $metaData['total'] ?? null,
            'per_page' => $metaData['per_page'] ?? null,
            'total_pages' => $metaData['total'] ?? null,
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以覆盖你的toResponse方法,看起来像:

public function toResponse($request)
{
    return $this->resource instanceof AbstractPaginator
                ? (new CustomPaginatedResourceResponse($this))->toResponse($request)
                : parent::toResponse($request);
}
Run Code Online (Sandbox Code Playgroud)

如果您想进一步自定义您的响应,您可以考虑覆盖覆盖其他方法。

解决方案 2:覆盖toResponseResourceCollection

PaginatedResourceResponse您可以toResponse使用类似代码的轻量级版本覆盖ResourceCollection 中的方法,而不是覆盖,如下所示:

public function toResponse($request)
{
    $data = $this->resolve($request);
    if ($data instanceof Collection) {
        $data = $data->all();
    }

    $paginated = $this->resource->toArray();
    // perform a dd($paginated) to see how $paginated looks like

    $json = array_merge_recursive(
        [
            self::$wrap => $data
        ],
        [
            'links' => [
                'first' => $paginated['first_page_url'] ?? null,
                'last' => $paginated['last_page_url'] ?? null,
                'prev' => $paginated['prev_page_url'] ?? null,
                'next' => $paginated['next_page_url'] ?? null,
            ],
            'meta' => [
                'current_page' => $metaData['current_page'] ?? null,
                'total_items' => $metaData['total'] ?? null,
                'per_page' => $metaData['per_page'] ?? null,
                'total_pages' => $metaData['total'] ?? null,
            ],
        ],
        $this->with($request),
        $this->additional
    );

    $status = $this->resource instanceof Model && $this->resource->wasRecentlyCreated ? 201 : 200;

    return response()->json($json, $status);
}
Run Code Online (Sandbox Code Playgroud)

解决方案 3:覆盖withResponse方法

一个更简单但可能不太强大的选项是withResponse像这样覆盖资源集合中的 :

public function withResponse($request, $response)
{
    $data = $response->getData(true);
    $prev = $data['links']['prev'];
    $next = $data['links']['next'];
    $self = $data['links']['self'];
    $data['links'] = compact('prev', 'next', 'self');
    $response->setData($data);
}
Run Code Online (Sandbox Code Playgroud)