Laravel 中 dingo API tranformer 返回自定義分頁格式資料

風吹過有夏天的味道發表於2019-07-03
{
    "message": "成功",
    "status_code": 200,
    "data": {
        "total": 46,
        "current_page": 1,
        "page_size": 11,
        "total_page": 5,
        "data": [
            {
                "id": 31,
                "name": "zKMp",
                "classification_id": 1,
                "imgs": [
                    {
                        "url": "123"
                    }
                ],
                "unit": "Mc",
                "price": 6.46,
                "status": 1,
                "user_id": 55,
                "created_at": "2019-06-25 11:51:37",
                "updated_at": "2019-06-25 11:51:37"
            },
            。。。
        ]
    }
}

實現

  • 轉化
    /**
     * 轉化組織分頁資料
     * @param $paginate
     * @param $transformer
     * @return array
     */
    public function paginateToApiData($paginate,$transformer)
    {
        if($paginate->isEmpty()){
            return [];
        }
        $total = $paginate->total();
        $current_page = $paginate->currentPage();
        $page_size = $paginate->perPage();
        $goods = $paginate->items();
        $data = [];
        foreach ($goods as $good){
            $data[] = $this->apiItem($good, $transformer);
        }
        return [
            'total'=>$total,
            'current_page'=>$current_page,
            'page_size'=>(int)$page_size,
            'total_page'=>$paginate->lastPage(),
            'data'=>$data
        ];
    }
  • controller 中返回

    // $paginate laravel分頁器
    return $this->success('成功',$this->service->paginateToApiData($paginate,new GoodsTransformer));
    
    //$this->success
    /**
    * 響應成功帶成功訊息
    * @param $message
    *@returnIlluminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Reponse
    */
    public function success($message,$data = [])
    {
    return response(['message'=>$message,'status_code'=>200, 'data'=>$data]);
    }

相關文章