【问题标题】:paginate method for data obtained from external api从外部api获取数据的分页方法
【发布时间】:2019-07-24 06:37:03
【问题描述】:

我想知道是否可以自动化从外部 API 获取的数据的分页过程,例如

$users = App\User::paginate(15);

对于模型。也许你知道任何包裹?我想做类似的东西

        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', 'https://xxx');
        $data = $res->getBody();
        $res = json_decode($data );
       ///pagination

您知道任何解决方案吗?是手动创建分页的唯一一种方法吗?

【问题讨论】:

    标签: laravel api


    【解决方案1】:

    你可以使用 Laravel 资源。

    首先:创建一个资源(我想你的 API 是关于 Post)

    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class Post extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return array
         */
        public function toArray($request)
        {
            return [
              'name' => $this->resource['name'],
              'title' => $this->resource['title']
    
            ];
        }
    }
    
    

    第二:创建资源集合

    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\ResourceCollection;
    
    class PostCollection extends ResourceCollection
    {
        public function toArray($request)
        {
            return [
                'data' => $this->collection
                    ->map
                    ->toArray($request)
                    ->all(),
                'links' => [
                    'self' => 'link-value',
                ],
            ];
        }
    }
    

    之后,您可以将您的 api 数据设置为这样的集合:

    $client = new \GuzzleHttp\Client();
    $res = $client->request('GET', 'https://xxx');
    $data = $res->getBody();
    $res = collect(json_decode($data));
    return PostCollection::make($res);
    

    要为您的资源集合添加分页,您可以这样做:

    $res = collect(json_decode($data));
    
    $page = request()->get('page');
    $perPage = 10;
    $paginator = new LengthAwarePaginator(
        $res->forPage($page, $perPage), $res->count(), $perPage, $page
    );
    
    return PostCollection::make($paginator);
    

    如需了解更多关于 Laravel 集合的信息,请访问 laravel documentation

    如需了解更多关于使用 Laravel 资源使用第三方 API 的信息,请访问 this great article

    【讨论】:

    • 感谢您的深入解释。
    猜你喜欢
    • 2017-07-06
    • 2011-12-21
    • 1970-01-01
    • 2021-04-25
    • 2019-11-19
    • 2016-03-11
    • 1970-01-01
    • 2017-12-06
    • 2021-06-23
    相关资源
    最近更新 更多