[英]How to get pagination links in resource collection - Laravel 5.7.19
我正在使用 laravel API 資源。 當我們不使用任何資源集合時,我們使用 paginate(10) 獲得分頁鏈接等。 但是當我使用 Resource::collection 時,我什么也得不到,只有我放入資源中的字段。
這是我的控制器
return response()->json([
"items" => LatestProjectsResource::collection(Project::has('pages')->where('type', $type)->latest()->paginate(20))
]);
這是我的資源
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->name,
'slug' => $this->slug,
'url' => $this->url,
'thumbnail' => new ThumbnailResource($this->thumbnail),
];
}
結果
我嘗試了在線社區的一些答案,包括這個Customizing Laravel 5.5 Api Resource Collection pagination one 但它不起作用
我試過$this->collection
但沒有運氣
請幫幫我。
我通過覆蓋常規資源類的collection
方法解決了這個問題。
public static function collection($data)
{
/* is_a() makes sure that you don't just match AbstractPaginator
* instances but also match anything that extends that class.
*/
if (is_a($data, \Illuminate\Pagination\AbstractPaginator::class)) {
$data->setCollection(
$data->getCollection()->map(function ($listing) {
return new static($listing);
})
);
return $data;
}
return parent::collection($data);
}
這只是檢查給定的數據是否是 Laravel 分頁器類的實例,如果是,它只是修改底層集合並返回相同的分頁器實例。 您可以將它放在抽象集合類或每個資源類中。
你可以得到像
use App\User;
use App\Http\Resources\UserCollection;
Route::get('/users', function () {
return new UserCollection(User::paginate());
});
請參閱文件
結果會像
{
"data": [
{
"id": 1,
"name": "Eladio Schroeder Sr.",
"email": "therese28@example.com",
},
{
"id": 2,
"name": "Liliana Mayert",
"email": "evandervort@example.com",
}
],
"links":{
"first": "http://example.com/pagination?page=1",
"last": "http://example.com/pagination?page=1",
"prev": null,
"next": null
},
"meta":{
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://example.com/pagination",
"per_page": 15,
"to": 10,
"total": 10
}
}
為了讓你的代碼干凈,制作一個 PaginationResource 來跨不同的集合使用,並為編輯分頁細節制作一個地方
然后在任何資源中添加您的分頁資源,如下所示
public function toArray($request) : Array
{
return [
'total' => $this->total(),
'count' => $this->count(),
'per_page' => $this->perPage(),
'current_page' => $this->currentPage(),
'total_pages' => $this->lastPage()
];
}
並將其添加到任何其他集合中
public function toArray($request) : Array
{
$pagination = new PaginationResource($this);
return [
'templates' => $this->collection,
$pagination::$wrap => $pagination,
];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.