Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 428
Clément Andraud Avatar asked Oct 11 '16 14:10

Clément Andraud


Video Answer


2 Answers

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']);
}
like image 157
jedrzej.kurylo Avatar answered Nov 20 '22 17:11

jedrzej.kurylo


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

like image 45
James Avatar answered Nov 20 '22 17:11

James