【问题标题】:Laravel api resources only queried dataLaravel api 资源只查询数据
【发布时间】:2020-01-13 17:40:36
【问题描述】:

根据json:api 标准,客户端可以请求端点仅返回响应中的特定字段,因此我的控制器中有此代码:

public function index(Request $request)
{
    $members = Member::query();

    if ($request->query('fields')) {
        $members->select($request->query('fields'));
    }

    return MemberResource::collection($members->paginate());
}

但由于资源包含所有字段,它仍将返回具有 null 值的其他字段。

我正在寻找一种干净的方法来仍然使用 api 资源,但只获取查询的字段,类似于 $this->whenloaded() $this->whenQueried() 之类的东西

【问题讨论】:

    标签: laravel


    【解决方案1】:

    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),
    

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 2020-06-13
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 2013-09-03
      • 2018-08-05
      相关资源
      最近更新 更多