Add a calculated field to Laravel model query

23,426

Solution 1

Add this in your Comment Model:

protected $appends = ['tag_translated'];

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

Hope this helps.

Solution 2

Yes there is? just add this to your Comment model

public function getTagTranslatedAttribute()
{
    return Lang::methodYouWish($this->tag);
}

then you can access this property from comment instance

$comment->tag_translated;

EDIT

You can modify your toArray method, just add it to Comment class

protected $appends = ['tag_translated'];

and then

$comment->toArray();

Solution 3

I was facing the same issue, and you just need to add two things:

The first one is the appends field:

protected $appends = ['field'];

The second one is the "getter":

public function getFieldAttribute()

At the end of the method name you need to add the "Attribute" suffix, and that's it.

Share:
23,426
Jonathan
Author by

Jonathan

Freelance programmer.

Updated on May 12, 2020

Comments

  • Jonathan
    Jonathan almost 4 years

    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?

  • Jonathan
    Jonathan almost 8 years
    Thanks! This will retrieve only that attribute, Id like to append it to the result obtained when invoking it through its parent model as in $post->comments. Then Id like to retrieve something like id,comment,tag,translated_tag.
  • Boyd Hemphill
    Boyd Hemphill almost 6 years
    I'd like to lobby for this to be the accepted answer. It is much more detailed and much more user. This is esp true after the edit.
  • Jonathan
    Jonathan almost 5 years
    Thanks! I learned also that if you dont add the $appends then the field is only retrieved when you specifically request for it as in $model->field.