代码之家  ›  专栏  ›  技术社区  ›  SaidbakR

如何向Laravel paginate json响应添加自定义属性

  •  0
  • SaidbakR  · 技术社区  · 6 年前

    我有以下简单的索引方法:

    public function index()
        {
           // dd(Poll::paginate(2));
          return response()->json(Poll::paginate(2),200);
        }
    

    {
    "current_page": 1,
    "data": [
    {
    "id": 1,
    "title": "I suppose?' said Alice. 'Why, you don't know.",
    "created_at": "2018-09-14 16:42:11",
    "updated_at": "2018-09-14 16:42:11"
    },
    {
    "id": 2,
    "title": "Alice; but she knew that it seemed quite.",
    "created_at": "2018-09-14 16:42:11",
    "updated_at": "2018-09-14 16:42:11"
    }
    ],
    "first_page_url": "http://127.0.0.1:8000/polls?page=1",
    "from": 1,
    "last_page": 6,
    "last_page_url": "http://127.0.0.1:8000/polls?page=6",
    "next_page_url": "http://127.0.0.1:8000/polls?page=2",
    "path": "http://127.0.0.1:8000/polls",
    "per_page": 2,
    "prev_page_url": null,
    "to": 2,
    "total": 11
    }
    

    我想在后面添加另一个数组属性 "total: 11" 属性,例如:

    ,
    "anotherData" : [
       "userId": 1,
       "userName": "john10",
       "message": "This is a message"
    ]
    

    我试过了 response()->json() 工作,所以它可以从 LengthAwarePaginator 对象的输出 Poll::paginate(2) this resource 在json对象中保存结果键?!

    1 回复  |  直到 6 年前
        1
  •  0
  •   SaidbakR    5 年前

    从被视为 resource above ,的 json() 方法获取一个数组,我猜,如果参数不是数组,它会尝试将其转换为数组,特别是如果它是类似 LengthAwarePaginator ,因此可以使用 toArray()

    我试过替换 return response()->json(Poll::paginate(2),200) return response()->json(Poll::paginate(2)->toArray,200) ,则得到相同的输出。因此,我决定将索引方法的代码替换为以下代码:

    public function index()
        {
            //dd(Poll::paginate(2)->toArray());
            $output = Poll::paginate(2)->toArray();
            $output['userData'] = ['userId' => \Auth::user()->id, 'userEmail' => \Auth::user()->email];
            return response()->json($output,200);
        }
    

    结果输出为:

    ...
    "path": "http://127.0.0.1:8000/polls",
    "per_page": 2,
    "prev_page_url": null,
    "to": 2,
    "total": 11,
    "userData": {
    "userId": 1,
    "userEmail": "lion@example.com"
    }
    }
    
        2
  •  0
  •   Dave Howson    4 年前

    如果您直接使用分页数据进行响应,更好的选择是将其包装在 Resource Collection adding meta data 去吧。

    CategoryController.php

    public function index()
    {
        return new CategoryCollection(Category::paginate(10));
    }
    

    public function toArray($request)
    {
        return [
            'status' => 1,
            'message' => 'Success',
            'data' => $this->collection,
        ];
    }
    

    Collection 延伸 JsonResource ,当从控制器返回时,您的响应将自动转换为JSON。