重写 API 资源分页数据

环境注意

laravel: 6.0+
5.8因资源内容不同,要根据不同情况调整

初期使用

return $this->success('',new UploadCollection($upload));

控制器文件trait

return response()->json([
        'code'=> 0,
        'message'=> $message,
        'data' => $data
],200);

直接使用

return new UploadCollection($upload);

Upload资源数据包裹中包含多余数据

"links": {
        "first": "http://locahost/api/upload?page=1",
        "last": "http://locahost/api/upload?page=10",
        "prev": null,
        "next": "http://locahost/api/upload?page=2"
    },
    "meta": {
        "current_page": 1,
        "from": 1,
        "last_page": 10,
        "path": "http://locahost/api/upload",
        "per_page": 15,
        "to": 15,
        "total": 148
    }

重写ResourceCollection

namespace App\Http\Resources\Json;

use Illuminate\Http\Resources\Json\ResourceCollection;

class BaseResourceCollection extends ResourceCollection
{
    /**
     * Create a paginate-aware HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    protected function preparePaginatedResponse($request)
    {
        if ($this->preserveAllQueryParameters) {
            $this->resource->appends($request->query());
        } elseif (! is_null($this->queryParameters)) {
            $this->resource->appends($this->queryParameters);
        }

        return (new CustomPaginatedResourceResponse($this))->toResponse($request);
    }

    /**
     * 返回应该和资源一起返回的其他数据数组
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function with($request)
    {
        return [
            'code' => 0,
            'msg'  => '',
        ];
    }
}

CustomPaginatedResourceResponse 文件

namespace App\Http\Resources\Json;

use Illuminate\Http\Resources\Json\PaginatedResourceResponse;

class CustomPaginatedResourceResponse extends PaginatedResourceResponse
{
    /**
     * Add the pagination information to the response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function paginationInformation($request)
    {
        $paginated = $this->resource->resource->toArray();

        return [
            // 'links' => $this->paginationLinks($paginated),
            'meta' => $this->meta($paginated),
        ];
    }

    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,
            'last_page' => $metaData['last_page'] ?? null,
            'total' => $metaData['total'] ?? null,
        ];
    }
}

修改后返回值

    "meta": {
        "current_page": 1,
        "last_page": 10,
        "total": 148
    },
    "code": 0,
    "msg": ""

引入重写BaseResourceCollection 即可正常使用,如果有更好的实现方式希望留下你的宝贵评论

本作品采用《CC 协议》,转载必须注明作者和本文链接
Image
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 16

我也是这么干的,继承这个类重写方法

5年前 评论
Image 莫须有 (楼主) 5年前

一直没用这个API资源。。。重新写了个方法整合最后的返回数据

5年前 评论
zhanghaidi

数据在单独返嘛?

5年前 评论
Image 莫须有 (楼主) 5年前

这个就很好啊! 学习了

5年前 评论

我是直接这样返回:

if (! function_exists('respond')) {
    /**
     * 生成响应体
     *
     * Date: 21/03/2018
     * @author George
     * @param array $data
     * @param string $message
     * @param int $code
     * @param array $header
     * @return JsonResponse
     */
    function respond($data = [], $message = '请求成功', $code = JsonResponse::HTTP_OK, array $header = []) {
        if ($data instanceof LengthAwarePaginator) {
            return new JsonResponse([
                'code' => $code,
                'message' => $message,
                'data' => $data->items(),
                'current_page' => $data->currentPage(),
                'from' => $data->firstItem(),
                'per_page' => $data->perPage(),
                'to' => $data->lastItem(),
                'last_page' => $data->lastPage(),
                'total' => $data->total(),
            ], $code, $header, JSON_UNESCAPED_UNICODE);
        } else {
            return new JsonResponse([
                'code' => $code,
                'message' => $message,
                'data' => $data ? $data : []
            ], $code, $header, JSON_UNESCAPED_UNICODE);
        }
    }
}
5年前 评论
Image 周小云 2年前

@GeorgeKing 这个也很不错,我仅仅是为了使用资源而使用

5年前 评论
5年前 评论
Image 莫须有 (楼主) 5年前
Image 小猪蹄子 (作者) 5年前

file

file 为啥我这个没有变化呢

5年前 评论
Image 莫须有 (楼主) 5年前
Image xiaoMaoLv (作者) 5年前
Image xiaoMaoLv (作者) 5年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!