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 ?
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']);
}
                        You could get the model's attributes with $post->getAttributes() which returns an array of attributes before any appends
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With