如何在Laravel api资源中对集合进行分页?
我有一个类别表,我需要获取所有属于该类别的产品,并对产品集合进行分页 控制器代码:如何在Laravel api资源中对集合进行分页?,laravel,api,Laravel,Api,我有一个类别表,我需要获取所有属于该类别的产品,并对产品集合进行分页 控制器代码: public function show($id) { $category = Category::find($id); if($category){ return new ProductByCategoryResource($category); } } 在ProductByCategoryResource中: <?php namespace App\Ht
public function show($id)
{
$category = Category::find($id);
if($category){
return new ProductByCategoryResource($category);
}
}
在ProductByCategoryResource
中:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\ProductResource;
class ProductByCategoryResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'category_name'=> $this->category,
'products'=> ProductResource::collection($this->products)
];
}
}
将其放入AppServiceProvider
文件中的boot
方法中:
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
然后在您的资源中简单地使用:
'products'=> ProductResource::collection($this->products)->paginate(10)