从外部api获取数据的分页方法

时间:2019-03-02 11:29:00

标签: laravel api

我想知道是否可以针对从

之类的外部API获取的数据自动执行分页过程
$users = App\User::paginate(15);

用于型号。也许您知道任何包裹吗?我想做类似的事情

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

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

1 个答案:

答案 0 :(得分:2)

您可以使用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

相关问题