1

I have a Term model who has a "parent" relationship that points to another term in the terms table. I load these relationships recursively, and return a Term resource. The resource references the taxonomy the term is related to.


class Term extends JsonResource {
  public function toArray($request) {
    return [
      'parent' => $this->whenLoaded('parent', function() {
        return Term::make($this->parent);
      }, $this-parent_id),
      'taxonomy' => $this->whenLoaded('taxonomy', function() {
        return Taxonomy::make($this->taxonomy);
      }, $this->taxonomy_id);
    ];
  }
}

The issue is that the taxonomy key appears on every parent term all the way up the tree:

    {
        "id": 48,
        "name": "Freestone Hills",
        "slug": "freestone-hills",
        "parent": {
            "id": 47,
            "name": "Sanoma Coast",
            "slug": "sanoma-coast",
            "parent": {
                "id": 47,
                "name": "California",
                "slug": "california",
                "taxonomy": 8 // or here
            },
            "taxonomy": 8 // but not here
        },
        "taxonomy": 8 // I want this here
    }

All parent terms will always belong to the same taxonomy so it's pointless to include the key anywhere except the root element.

Is there any way to say "only show this key if we are at the top level"? I'd rather not duplicate the information for the taxonomy, especially when there's an entire object for the taxonomy when I actually do load in that relationship.

mindfullsilence
  • 344
  • 9
  • 23

0 Answers0