Laravel资源集合 - 分页 - JSON 响应错误



我想在Laravel API上做分页。因此,我想获取数据和状态代码类型。

控制器:

public function index()
{
$data = PersonCollection::collection(Person::paginate(2));
return response()->json($data, 200);
}

人员收藏资源 :

public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone' => $this->phone,
'city' => $this->city,
'href' => [
'link' => route('person.show', $this->id),
],
];
}

输出:

https://i.hizliresim.com/LvlBzj.png

[
{
"id": 1,
"first_name": "Burak Ali",
"last_name": "Ildır",
"email": "burak@gmail.com",
"phone": "376.395.7233",
"city": "Koelpinstad",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/1"
}
},
{
"id": 2,
"first_name": "Vena",
"last_name": "Spinka",
"email": "shields.carolyn@example.org",
"phone": "716-268-7788 x092",
"city": "South Gudrunbury",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/2"
}
}
]

但我想要。

https://i.hizliresim.com/LvlBWo.png

{
"data": [
{
"id": 1,
"first_name": "Burak Ali",
"last_name": "Ildır",
"email": "burak@gmail.com",
"phone": "376.395.7233",
"city": "Koelpinstad",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/1"
}
},
{
"id": 2,
"first_name": "Vena",
"last_name": "Spinka",
"email": "shields.carolyn@example.org",
"phone": "716-268-7788 x092",
"city": "South Gudrunbury",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/2"
}
}
],
"links": {
"first": "http://127.0.0.1:8000/api/v1/person?page=1",
"last": "http://127.0.0.1:8000/api/v1/person?page=26",
"prev": null,
"next": "http://127.0.0.1:8000/api/v1/person?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 26,
"path": "http://127.0.0.1:8000/api/v1/person",
"per_page": 2,
"to": 2,
"total": 52
}
}

我想要其他页面链接。但是当我将其转换为 JSON 数据时,链接和元数据不会出现。

资源集合描述如何将模型集合作为 JSON 传输。

您似乎将其用于单个模型。您需要的是:

public function toArray($request)
{
return $this->collection->map(function ($person) {
return [
'id' => $person->id,
'first_name' => $person->first_name,
'last_name' => $person->last_name,
'email' => $person->email,
'phone' => $person->phone,
'city' => $person->city,
'href' => [
'link' => route('person.show', $person->id),
],
];
});
}

但是,建议的方法是在同一命名空间中创建一个PersonResource,并在该类中实现toArray($request)

class Person extends Resource //The name is important
{
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone' => $this->phone,
'city' => $this->city,
'href' => [
'link' => route('person.show', $this->id),
],
];
}
}

人物收藏

class PersonCollection extends ResourceCollection
{ 
// This class is intentionally empty
}

最后,你应该让Laravel处理如何做出回应:

public function index()
{
$data = PersonCollection::collection(Person::paginate(2));
return $data->toResponse();
}

资源集合的默认行为是查找名称类似于集合但删除Collection部分的资源(在本例中PersonCollection将查找Person资源(。

这应确保根据资源转换每个模型,并保持分页行为。

最新更新