![](/img/trans.png)
[英]How to get pagination links in resource collection - Laravel 5.7.19
[英]Laravel Collection Pagination Problem on API Resource
如果我使用 Laravel 的分頁方法,下面的代碼給出了Uncaught ErrorException: Trying to get property 'id' of non-object in...
錯誤。 如果我使用all()
,它工作正常。
$articles = Models\Article::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
]
}
為什么它返回頁碼,而不是完整的 object? 我想念什么? 我檢查了文檔,但是當我使用分頁時,它似乎是由 Laravel 處理的。
我想到了。 用collect
助手包裝查詢結果是不必要的。 現在可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.