Laravel分页资源不会添加元 [英] Laravel paginate resources won't add meta

查看:30
本文介绍了Laravel分页资源不会添加元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

基于

代码

控制器

 公共函数index(){$ products = ProductFrontResource :: collection(Product :: orderby('id','desc')-> with(['photos','seo','tags','variations','variations.children','options','options.children','categories'])-> where('active','yes')-> paginate(8));返回response()-> json(['数据'=>$个产品,'message'=>产品检索成功.",]);} 

有什么想法吗?

解决方案

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

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

 公共函数index(){$ data =产品:: orderby('id','desc')-> with([['photos','seo','tags','variations','variations.children','options','options.children','categories'])-> where('active','yes')-> paginate(8);$ products = ProductFrontResource :: collection($ data);返回$ products;} 

其他元数据

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

是的,您可以 添加元数据 .

 公共函数toArray($ request){返回 ['数据'=>$ this->集合,'message'=>产品检索成功."];} 

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?

解决方案

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.'
    ];
}

这篇关于Laravel分页资源不会添加元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆