I have some problem with laravel and protected $attributes and mutators.
I have user ranking with points. I want add to User Model another attribution with ranking Position.
In user model I have public function like this:
public function getRankPositionAttribute(){
$userPoints= Ranking::where('user_id','=',$this->id)->first();
$userPosition = Ranking::where('points','>',$userPoints->points)->count()+1;
return $userPosition;
}
I also set:
protected $attributes = array('RankPosition'='');
But it's not working (I don't see value like RankPosition in attributes). Strange thing is that when I add (for example) value like this:
protected $attributes =array('test'=>'yes');
Laravel also don't see test...
But when I add this:
protected $appends = array('RankPosition');
and in my controller I find all user and get response to json then in json response i see value like RankPosition with the correct value... :(
What Im doing wrong? Why "my laravel" skips protected $attributes?
Please help me.
This is because if you provide protected $attributes
in your class then Laravel doesn't override it when the source of attributes are the table . Here the source of $attributes
is database column.
But when you do something like this:
$user = new User;
then you will see a test
attribute.
So to dynamically adding the attributes you should use appends
property on the model.