首页 > 解决方案 > 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()

标签: laravel

解决方案


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

推荐阅读