首页 > 解决方案 > 如何进行 API 资源分页?

问题描述

我创建了一个 API 并进行了自定义。查看文档,我尝试了几种方法,但不知何故我无法进行分页。你能帮助我吗?

PostResource.php

<?php

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'            => $this->id,
            'image'         => $this->image,
            'description'   => $this->description,
            'created_at'    => $this->created_at,
            'updated_at'    => $this->updated_at,
            'user'          => new UserResource($this->user),
            'comments'      => CommentResource::collection($this->comment),
        ];
    }
}

PostController.php

public function res() {
        $post_all_item = Posts::all();
        return response()->json(PostResource::collection($post_all_item),200);

    }

标签: laravellaravel-7

解决方案


这是在 laravel 中对集合进行分页的方法:

$post_all_item = Posts::paginate(15); //will paginate 15 posts per page
return PostResource::collection($post_all_item); //will be converted to Json automatically

注意1:模型名称应该是单数,例如。Post代替Posts

注意 2:不需要将资源集合转换为 json 响应,Laravel 会自动完成

注意3:在资源文件中,使用以下命令检查关系是否存在whenLoaded

'user'     => new UserResource($this->whenLoaded('user')), //with resource
'comments' => $this->whenLoaded('comments'), //without resource

推荐阅读