W
W
WebDev2018-09-27 13:16:31
Laravel
WebDev, 2018-09-27 13:16:31

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

That is, now I can access the commaTags property of the Article model and get a list of tags in one line.
Now I need to select users with their articles with commaTags property.
For this, I fill in the $with property in the User model.
class User
{
    protected $with = ['article.commaTags'];
}

So that when selecting users, their articles are always added to them, and tags separated by commas to the articles.
But this entry throws an error. I guess because commaTags is not a real field, but artificially created.
How to implement the idea?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2018-09-27
@kirill-93

class Article 
{
    protected $appends = ['commaTags'];
}

PS
public function getCommaTagsAttribute()
{
    $this->tags->implode('name', ', ');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question