Laravel paginate resources won't add meta

烂漫一生 提交于 2021-02-05 07:26:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!