laravel - 如何进行 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);
}
解决方案
这是在 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
推荐阅读
- dependencies - 如何将lib文件夹从WEB-INF提取到其他位置
- angular - 提供 ng 服务时出现 CLI 错误
- python - 如何在 django 的基于类的列表视图中添加点赞按钮
- c++ - 将 cv::Mat 打印到 std::cout 与 operator<< 多维数组的内存异常错误
- python - 如何使用 python 将列从 CSV 文件转换为 json,以便键和值对来自 CSV 的不同列?
- mysql - 为每个选定的记录插入记录
- react-native - 如何将组件添加到卡片标题容器 react-native-elements
- python - 是否可以告诉词干分析器忽略特定语言的单词?
- html - 下拉子菜单打开与后退按钮重叠的主菜单
- node.js - Nodejs全局变量范围问题