7
votes

I'm working with Laravel 5.3 and in a Model Post, I have an appends attributes :

/*
* toJson
*/
protected $appends = ['count'];

And the magic method :

public function getCountAttribute()
    {
        return Offer::where('id', '=', $this->id)->count();
    }

So, when I get a Post model with eloquent like Post::get(), and get the return with json for example, I ALWAYS have this attribute count in my object.

How can I specify if I want or not this or another appends atribute ?

2
Post::get() isn't a valid method, do you mean all?Styphon
Yeah, was just for the exampleClément Andraud

2 Answers

6
votes

I checked how Eloquent models get serialized and unfortunately list of fields to be appended is not shared between all instances of given Model and the only way I see to achieve what you need is to iterate through the result set and explicitly enable append for selected attributes:

$posts = Post::all();

foreach ($posts as $post) {
  // if you want to add new fields to the fields that are already appended
  $post->append('count');

  // OR if you want to overwrite the default list of appended fields
  $post->setAppends(['count']);
}
1
votes

You could get the model's attributes with $post->getAttributes() which returns an array of attributes before any appends