CleanCode
CleanCode

Reputation: 384

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

Upvotes: 2

Views: 486

Answers (1)

CleanCode
CleanCode

Reputation: 384

Enhanced version of Yossel's answer.

public function whenExists($field, $value = null)
{
  return $this->when(array_key_exists($field, $this->resource->toArray()), $value ?? $this->$field);
}

this way I can reuse the field as the value

"first_name" => $this->whenExists("first_name"),

instead of

"first_name" => $this->whenExists("first_name", $this->first_name),

Upvotes: 3

Related Questions