API资源上的Laravel集合分页问题



如果我使用Laravel的分页方法,下面的代码会给出Uncaught ErrorException: Trying to get property 'id' of non-object in...错误。如果我使用all(),它可以正常工作。

$articles = ModelsArticle::paginate(); // Eloquent collection
return Article::collection(collect($articles));

文章.php

class Notification extends JsonResource
{
public function toArray($request)
{
return [
'id'      => $this->resource->id,
'title'   => $this->resource->title,
];
}
}

我还尝试创建一个ResourceCollection并将查询结果发送给它,但结果是一样的。

Collection {#547
#items: array:12 [
"current_page" => 1
"data" => array:1 [
0 => array:10 [
"id" => 1
"title" => "Test"
"body"" => "test"
]
]
"first_page_url" => "https://localhost/api/v1/articles?page=1"
"from" => 1
"last_page" => 1
"last_page_url" => "https://localhost/api/v1/articles?page=1"
"next_page_url" => null
"path" => "https://localhost/api/v1/articles"
"per_page" => 15
"prev_page_url" => null
"to" => 1
"total" => 1
]
}

为什么它返回页码,而不是完整的对象?我想念什么?我检查了文档,但当我使用分页时,它似乎是由Laravel处理的。

我想明白了。不需要用collect帮助程序包装查询结果。它现在起作用了。

最新更新