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