php - Laravel 分页资源不会添加元

标签 php laravel

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

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

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

但我的数据是这样返回的:

one

代码
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/

相关文章:

php - mysql 和 php select * 查询不起作用

PHP:重构为面向对象——如何对连接建模

laravel - 是否可以从 laravel 中的公共(public)文件夹渲染 View

php - 表中不存在资源时如何重新路由到另一个 View (Laravel 4)

javascript - 在 Laravel Elixir 升级后使用严格添加到每个文件 - 损坏的脚本

laravel addSelectRaw() - 如何在 addSelect() 中绑定(bind)变量?

php - 使用 Safari 和 IE 时服务器端问题的常见原因

php - UTF-8贯穿始终

php - 使用嵌套的 ManyToOne 和 OneToMany 查询复杂的 Doctrine 关系

php - 带破折号的 Laravel 自定义命令参数