Jonathan
Jonathan

Reputation: 522

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?

Upvotes: 18

Views: 35477

Answers (3)

Daniel Azamar
Daniel Azamar

Reputation: 692

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.

Upvotes: 6

huuuk
huuuk

Reputation: 4795

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

Upvotes: 15

Osama Sayed
Osama Sayed

Reputation: 2023

Add this in your Comment Model:

protected $appends = ['tag_translated'];

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

Hope this helps.

Upvotes: 42

Related Questions