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')),
];
0

2 Answers 2

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
            );
        }
    ), 
];
Sign up to request clarification or add additional context in comments.

Comments

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.