【问题标题】:Laravel paginate resources won't add metaLaravel 分页资源不会添加元
【发布时间】:2020-05-17 18:53:42
【问题描述】:

我有以 JSON 格式返回的资源数据。当我尝试使用分页获取数据时,它不包含元数据。

基于documentation 我的数据应该包含在元数据中,例如:

"meta":{
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "http://example.com/pagination",
    "per_page": 15,
    "to": 10,
    "total": 10
}

但我的数据返回如下:

代码

controller

public function index()
{
    $products = ProductFrontResource::collection(Product::orderby('id', 'desc')->with(['photos', 'seo', 'tags', 'variations', 'variations.children', 'options', 'options.children', 'categories'])->where('active', 'yes')->paginate(8));
    return response()->json([
        'data' => $products,
        'message' => 'Products retrieved successfully.',
    ]);
}

有什么想法吗?

【问题讨论】:

  • 我认为你也必须使用分页功能:ProductFrontResource::collection (another query->paginate(8))->paginate(8);
  • @MubasharIqbal 抱歉没有明白你的意思!请给个样品好吗?

标签: php laravel


【解决方案1】:

您不需要使用response()。 Laravel 的资源类让你可以轻松地将模型和模型集合转换为 JSON。

每个资源类都定义了一个toArray 方法,该方法返回在发送响应时应转换为 JSON 的属性数组。

public function index()
{
    $data = Product::orderby('id', 'desc')
        ->with(['photos', 'seo', 'tags', 'variations', 'variations.children', 'options', 'options.children', 'categories'])
        ->where('active', 'yes')
        ->paginate(8);

    $products = ProductFrontResource::collection($data);

    return $products;
}

其他元数据

'message' => '产品检索成功。'

是的,你可以Adding Meta Data

public function toArray($request)
{
    return [
        'data' => $this->collection,
        'message' => 'Products retrieved successfully.'
    ];
}

【讨论】:

  • 谢谢它的工作,但我认为你需要编辑 return $product;return $products;
  • 如果我想转换集合怎么办?根据文档,我可以覆盖 toArray 方法吗?但是当我这样做时,它给了我一个错误:```未定义的属性:Illuminate\Pagination\LengthAwarePaginator::$id ```
猜你喜欢
  • 2021-01-05
  • 2018-07-20
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
相关资源
最近更新 更多