Answer the question
In order to leave comments, you need to log in
How to add a generated field of the related model to the response when fetching?
There are models User, Article, Tag
User - users, Article - articles of users, Tag - tags of articles.
In the Article Model, added a method to get all tags in one line, separated by commas.
class Article
{
public function tags()
{
return $this->belongsToMany('App\Models\Tag');
}
public function getCommaTagsAttribute()
{
$tags = [];
foreach ($this->tags as $tag) {
$tags[] = $tag->name;
}
return implode(',', $tags);
}
}
class User
{
protected $with = ['article.commaTags'];
}
Answer the question
In order to leave comments, you need to log in
class Article
{
protected $appends = ['commaTags'];
}
public function getCommaTagsAttribute()
{
$this->tags->implode('name', ', ');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question