Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Laravel api资源中对集合进行分页?_Laravel_Api - Fatal编程技术网

如何在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)