问题
I have resources data returning in JSON. When I try to get my data with paginate it is not included meta data.
Based on documentation my data supposed to be included meta like:
"meta":{
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://example.com/pagination",
"per_page": 15,
"to": 10,
"total": 10
}
but my data is returning like this:
Code
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.',
]);
}
Any idea?
回答1:
You don't need to use response()
. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.
Every resource class defines a toArray
method which returns the array of attributes that should be converted to JSON when sending the response.
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;
}
Additional Meta Data
'message' => 'Products retrieved successfully.'
Yes, you can Adding Meta Data.
public function toArray($request)
{
return [
'data' => $this->collection,
'message' => 'Products retrieved successfully.'
];
}
来源:https://stackoverflow.com/questions/60015140/laravel-paginate-resources-wont-add-meta