0

I have the following resource being returned:


{
  "id": "b93244c5-0c1e-4388-bd61-fd577b5c7c57",
  "state": 3,
  "createdAt": "2022-08-03T13:58:27.000000Z",
  "attendee": {
    "id": "5a0f730a-dcc7-4937-9a6a-bb9fe4a9285c",
    "about": "...",
    "firstName": "Bobby",
    "lastName": "Spencer",
    "timezone": "Atlantic/Azores",
    "username": "at-sed-2748",
    "avatar": null,
    "fullName": "Bobby Spencer"
  }
}

I would like to add email attribute to attendee ONLY if the logged user meets some condition. I assume that I would use additional but for some reason its not working:

class MeetupAttendeeResource extends JsonResource
{
    public function toArray($request)
    {
        /** @var Meetup $meetup */
        $meetup = $request->meetup;

        /** @var User $loggedUser */
        $loggedUser = $request->user();

        /** @var MeetupAttendeeService $meetupAttendeeService */
        $meetupAttendeeService = app()->make(MeetupAttendeeService::class);

        $attendee = (new UserResource($this->attendee));

        if ($meetupAttendeeService->canSeeEmail($loggedUser, $meetup)) {
            $attendee->additional(['email' => $this->attendee->email]);
        }

        return [
            'id' => $this->id,
            'state' => $this->state->value,
            'createdAt' => $this->created_at,
            'attendee' => $attendee,
            'meetup' => new MeetupResource($this->whenLoaded('meetup')),
        ];
    }
}

Why it's not adding email field? I have tried hardcoding it:

if (true) {
  $attendee->additional(['email' => $this->attendee->email]);
}

but still, it doesn't get added.

Bruno Francisco
  • 3,841
  • 4
  • 31
  • 61

1 Answers1

0

If you check the documentation for adding resources to responses, it says this (emphasis is mine):

Sometimes you may wish to only include certain meta data with a resource response if the resource is the outermost resource being returned. Typically, this includes meta information about the response as a whole.

This section is where the additional() method is mentioned:

You may also add top-level data when constructing resource instances in your route or controller. The additional method, which is available on all resources, accepts an array of data that should be added to the resource response.

So because your resource is nested inside the response, you can't use the additional() method to add the information.

Maybe create the resource with a null value for that property, and only change it as needed.

miken32
  • 42,008
  • 16
  • 111
  • 154