skip to Main Content

I am using a Laravel Resource to return my object. The object has optional relationships. My Resource code so far is below and is working as expected:

public function toArray(Request $request): array
{
    return [
        'id'                 => (string) $this->id,
        'attributes'         => [
            'name'             => $this->name,
            'status_id'        => $this->status_id,
            'created_at'       => $this->created_at,
            'updated_at'       => $this->updated_at,
        ],
        'relationships' => [
            'status'        => $this->whenLoaded('status'),
        ]
    ];
}

But I would like for the "status" relationship to only include one field from the model – the name. I thought just appending ->name would work. i.e. 'status' => $this->whenLoaded('status')->name,

This does work when the relationship is loaded, but generates an error when the relationship does not exist.

Is there any way to use whenLoaded and show only one field?

2

Answers


  1. Chosen as BEST ANSWER

    I think I have found the answer.

    public function toArray(Request $request): array
    {
        return [
            'id'                 => (string) $this->id,
            'attributes'         => [
                'name'             => $this->name,
                'status_id'        => $this->status_id,
                'created_at'       => $this->created_at,
                'updated_at'       => $this->updated_at,
            ],
            'relationships' => [
                'status' => $this->when(
                    $this->resource->relationLoaded('status'), function ()
                    {
                        return $this->resource->status->name;
                    }),
            ]
        ];
    }
    

  2. You can use the optional helper function provided by Laravel. The optional function accepts the object you want to work with and returns a new, nullable object. This way, you can safely access the "name" attribute even if the relationship is not loaded.

    public function toArray(Request $request): array
    {
        return [
            'id'          => (string) $this->id,
            'attributes'  => [
                'name'      => $this->name,
                'status_id' => $this->status_id,
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ],
            'relationships' => [
                'status' => optional($this->whenLoaded('status'))->only('name'),
            ],
        ];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search