Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a calculated field to Laravel model query

I have a controller which has a query such as this one:

$post = Post::find($id);
$comments = $post->comments;

Where a post has many comments and a comment belongs to one post. The comments model has an id,comment,tag field.

What I want to do is that for any query such as this one, the model returns the fields id, comment, tag and tag_translated, where the latter is just a translation of the tag using the Lang facade.

I could solve this by using a for on the controller which iterates over the $comments and adds the field, however Ill have to do that for every controller that requires the tag_translared field. Is there a way to ask the model to include such a field?

like image 782
Jonathan Avatar asked Jun 30 '16 03:06

Jonathan


1 Answers

Add this in your Comment Model:

protected $appends = ['tag_translated'];

public function getTagTranslatedAttribute()
{
    return 'the translated tag';
}

Hope this helps.

like image 183
Osama Sayed Avatar answered Oct 17 '22 07:10

Osama Sayed