我想知道是否可以自动化从外部 API 获取的数据的分页过程,例如
$users = App\User::paginate(15);
Run Code Online (Sandbox Code Playgroud)
对于模型。也许你知道有什么包吗?我想做那样的东西
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://xxx');
$data = $res->getBody();
$res = json_decode($data );
///pagination
Run Code Online (Sandbox Code Playgroud)
你知道有什么解决办法吗?手动创建分页是唯一的一种方法吗?
您可以使用 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']
];
}
}
Run Code Online (Sandbox Code Playgroud)
第二:创建资源集合
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',
],
];
}
}
Run Code Online (Sandbox Code Playgroud)
之后你可以将 api 数据设置为集合,如下所示:
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://xxx');
$data = $res->getBody();
$res = collect(json_decode($data));
return PostCollection::make($res);
Run Code Online (Sandbox Code Playgroud)
为了向您的资源集合添加分页,您可以这样做:
$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);
Run Code Online (Sandbox Code Playgroud)
要阅读有关 Laravel 集合的更多信息,请访问laravel 文档。
要了解有关使用 Laravel 资源使用第三方 API 的更多信息,请访问这篇精彩文章。
| 归档时间: |
|
| 查看次数: |
1999 次 |
| 最近记录: |