2

Id like to overwrite a relationship attribute like the following:

$article['tags'] = $article->tags->pluck('title');
return compact('article');

It fails because it returns the tags attribute as an array of objects instead of an array of title strings. The API consumer needs the data in that form. This also reduces the size of the payload.

My current work around is to add another attribute and unset the original one.

$article['tagged'] = $article->tags->pluck('title');
unset($article['tags']);
return compact('article');

But I wish it was simpler and straightforward.

5
  • 1
    try $article['tags'] = $article->tags()->pluck('title'); Commented Apr 24, 2018 at 5:35
  • Why not you just return title from tags relation instead ? Commented Apr 24, 2018 at 5:36
  • @Sohel0415 yours is the simple answer. Maybe add it below for me to accept? Commented Apr 24, 2018 at 5:52
  • @TechyTimo ok, i will add, thanks Commented Apr 24, 2018 at 5:52
  • @C2486 That yields an error - return $this->hasMany('App\Tag')->pluck('title'); // must return a relationship instance. Please provide your example as an answer below Commented Apr 24, 2018 at 5:57

2 Answers 2

1

Use the relation method tags() to get the title array.

$article['tags'] = $article->tags()->pluck('title');
Sign up to request clarification or add additional context in comments.

Comments

1

For overriding use setRelation(key, value):

$article->setRelation('tags', $article->tags()->pluck('title'));

^ This assumes you didn't preload the relationship. If you did, just remove the parenthesis from ->tags() (same as in your question: ->tags->pluck('title')).

For unsetting a single relationship, there's no available method. You could use ->setRelations(array) though.

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.