1

From here, I want to put data from relationship to my API resources.

With one key and one relationship, it works. But, with two different key and two same relationship, it doesn't.

My goal is :

  • If x relationship is loaded, use this data as key "a".
  • If y relationship is loaded, use this data as key "a".

What have I tried

  1. "Post" object with one key named "comments", whenLoaded "comments" relationship. (works)

  2. "Post" object with two key named "comments" and "comments". First "comments" is created whenLoaded "comments" relationship and second "comments" is created whenLoaded "comments_by_tag" relationship.

Then, I load "Post" with "comments" relationship (failed). And load "comments_by_tag" relationship (works).

  1. "Post" object with two key named "comments" and "comments". Now, I change the position of those which second "comments" is the first and first "comments" is the second.

Then, I load "Post" with "comments" relationship (works). And load "comments_by_tag" relationship (failed).

This is my code on

return [
  'comments' => CommentItem::collection($this->whenLoaded('comments')),
  'comments' => CommentItem::collection($this->whenLoaded('comments_by_tag')),
];
Alfan Zain
  • 55
  • 7

2 Answers2

1

Not as elegant, but does what you need. The ->relationLoaded(relationName) checks if it's loaded.

return [
    'comments' => $this->when(
        $this->relationLoaded('comments') 
        || $this->relationLoaded('comments_by_tag'),
        function () {
            return CommentItem::collection(
                $this->relationLoaded('comments')
                    ? $this->comments
                    : $this->comments_by_tag
            );
        }
    ), 
];
DevK
  • 9,597
  • 2
  • 26
  • 48
0

By simply check the value of the whenLoaded method.

whenLoaded method returns null if there is no loaded relation.

if ($comments = $this->whenLoaded('comments')) {
    return ['comments' => $comments]
} else if ($commentsByTag = $this->whenLoaded('comments_by_tag')) {
    return ['comments' => $commentsByTag];
}
hassan
  • 7,812
  • 2
  • 25
  • 36