Laravel Protected Attributes and Mutators

I have a problem with laravel and protected $ attributes and mutators.

I have a user rating with points. I want to add another attribution with a ranking position to the User Model.

In the user model, I have a public function:

public function getRankPositionAttribute(){
    $userPoints= Ranking::where('user_id','=',$this->id)->first();
    $userPosition = Ranking::where('points','>',$userPoints->points)->count()+1;
    return $userPosition;
    }

I also installed:

 protected $attributes = array('RankPosition'='');

But it does not work (I do not see such value as RankPosition in attributes). The strange thing is that when I add (for example) a value like this:

protected $attributes =array('test'=>'yes'); 

Laravel also does not see the test ...

But when I add this:

protected $appends = array('RankPosition');

and in my controller I find all users and get a response in json, and then in the json answer I see a value similar to RankPosition with the correct value ... :(

What am I doing wrong? Why does "my laravel" skip the $ protected attributes?

Please help me.

+4
1

, protected $attributes , Laravel , . $attributes .

- :

$user = new User;

test.

, appends .

+2

Source: https://habr.com/ru/post/1660605/


All Articles