重写 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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 16

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

3年前 评论
莫须有 (楼主) 3年前

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

3年前 评论
zhanghaidi

数据在单独返嘛?

3年前 评论
莫须有 (楼主) 3年前

这个就很好啊! 学习了

3年前 评论

我是直接这样返回:

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);
        }
    }
}
3年前 评论
周小云 3个月前

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

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

file

file 为啥我这个没有变化呢

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

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