我有以 JSON 形式返回的资源数据。当我尝试使用 paginate 获取我的数据时,它不包含元数据。
基于 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.',
]);
}
任何的想法?
最佳答案
您不需要使用 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' => 'Products retrieved successfully.'
是的,您可以 Adding Meta Data .
public function toArray($request)
{
return [
'data' => $this->collection,
'message' => 'Products retrieved successfully.'
];
}
关于php - Laravel 分页资源不会添加元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015140/