18

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
  • 512
  • 2
  • 5
  • 17
  • 1
    http://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load see this – Mahdi Youseftabar Jun 30 '16 at 03:47
  • Does this answer your question? [Add a custom attribute to a Laravel / Eloquent model on load?](https://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load) – M at Mar 11 '21 at 06:36

3 Answers3

41

Add this in your Comment Model:

protected $appends = ['tag_translated'];

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

Hope this helps.

Osama Sayed
  • 1,993
  • 15
  • 15
13

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();
huuuk
  • 4,597
  • 2
  • 20
  • 27
  • 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. – Jonathan Jun 30 '16 at 21:44
  • 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. – Boyd Hemphill Jul 01 '18 at 17:19
7

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.

Daniel Azamar
  • 672
  • 7
  • 8
  • 3
    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. – Jonathan May 12 '19 at 04:48