将自定义元数据合并到laravel中的分页响应

时间:2018-09-05 06:50:06

标签: php laravel pagination

我的控制器中包含以下代码:

公共功能索引(SaleRequest $ request,$ id)     {

    try {
        $from = Carbon::parse($request->query->get('from', '1970-01-01'));
        $till = Carbon::parse($request->query->get('till', Carbon::now()))->endOfDay();
    } catch (\Exception $e) {
        return response()->json([
            'error' => 'Invalid time range or data',
        ], 400);
    }

    $includes = ['product', 'price'];

    $seller = $this->resellerRepository->findOrFail($id);

    $paginator = $this->parseRequest($request, $seller)->with($includes)->paginate();

    $sales = $paginator->items();

    $data = fractal()
        ->collection($sales, new SaleTransformer())
        ->parseIncludes($includes)
        ->paginateWith(new IlluminatePaginatorAdapter($paginator))
        ->toArray();

    $sum = 0;
    foreach ($sales as $sale) {
        $sum = $sum + $sale->price->value_origin;
    }

    $data['meta'] = [
        'from'          => $from->toDateString(),
        'till'          => $till->toDateString(),
        'count_total'   => count($data['data']),
        'total'         => $sum / 100,
    ];

    return response()->json($data);
}

在我的回应中,我没有从分页器获取分页元数据。我只得到自定义元数据:

"meta": {
    "from": "1970-01-01",
    "till": "2018-09-05",
    "count_total": 5,
    "total": 80
}

我的方法是将分页数据手动添加到元数据,例如:

    $data['meta'] = [
        'from'          => $from->toDateString(),
        'till'          => $till->toDateString(),
        'count_total'   => count($data['data']),
        'total_sum'         => $sum / 100,
        'pagination' => [
            'current_page' => $paginator->currentPage(),
            'last_page' => $paginator->lastPage(),
            'total' => $paginator->total(),
            'count' => $paginator->count(),
            'per_page' => $paginator->perPage(),
        ]
    ];

有更好的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

答案是更新我的ide_helper方法,因为Fractal为此提供了方法addMeta()。

    $data = fractal()
        ->collection($items, new ItemTransformer())
        ->paginateWith(new IlluminatePaginatorAdapter($paginator))
        ->addMeta([
            'from' => $from->toDateString(),
            'till' => $till->toDateString(),
            'total_sum' => $totalSum,
            'page_sum' => $sum,
        ])
        ->toArray();