laravel - Laravel api resources only queried data
问题描述
As per json:api standards a client can request that an endpoint return only specific fields in the response, so I have this code in my controller:
public function index(Request $request)
{
$members = Member::query();
if ($request->query('fields')) {
$members->select($request->query('fields'));
}
return MemberResource::collection($members->paginate());
}
but since the resource has all fields it will still return the other fields with null
values.
I am looking for a clean way to still use api resources but getting only the queried fields, similar to $this->whenloaded()
something like $this->whenQueried()
解决方案
Yossel答案的增强版。
public function whenExists($field, $value = null)
{
return $this->when(array_key_exists($field, $this->resource->toArray()), $value ?? $this->$field);
}
这样我可以重用该字段作为值
"first_name" => $this->whenExists("first_name"),
代替
"first_name" => $this->whenExists("first_name", $this->first_name),
推荐阅读
- sql - 如何使用knexjs在postgresql中搜索具有特殊字符和其他字符的文本?
- php - PHP解析巨大的XML文件
- node.js - 我无法理解何时在 node.js 中使用 / 、 ./ 和 ../
- javascript - ReactJs:输入值不会因为使用 Array.map 而改变
- python - 在 Python 中使用这种类型的代码重新启动 Yes 或 No
- python - 使用 mongoengine 进行烧瓶舞的自定义 Oauth 令牌存储
- c++ - C++ 程序以一些返回值退出而不运行一些行?
- java - Apache Tomcat 10.0.0-M1 使用 JSP 绝对 uri http://java.sun.com/jsp/jstl/core 无法解析
- javascript - 单击 + 按钮,添加字段
- protocol-buffers - 什么是弃用协议缓冲区 v3 中的字段的最佳方法,保留与弃用 = true?