Clément Andraud
Clément Andraud

Reputation: 9269

Laravel get model without appends attributes

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 ?

Upvotes: 7

Views: 7394

Answers (2)

James
James

Reputation: 441

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

Upvotes: 1

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

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']);
}

Upvotes: 6

Related Questions