P
P
photosho2016-01-12 19:15:39
Laravel
photosho, 2016-01-12 19:15:39

Why doesn't the getAttribute method write class properties?

Hello everyone again. The article model has some method "getUserIdAttribute()" that reads the ID of the author of this article. Also, there is a public property "author" which is an array. The above method writes the necessary author parameters to this property:

public function getUserIdAttribute($value) {
  $this->author['name'] = User::find($value)->username;
  $this->author['id'] = $value;
}

Unfortunately, for some reason, the data does not want to be written to the $author property. If you create a public function inside the model class that performs the same actions, then it will normally write the $author property. Is this how it should be or am I doing something wrong?
And the second question. Line: User::find($value)->username, as far as I understand, reads all user fields under the number $value from the database and then takes the value of the "username" field? Should I do something like this to only count the required fields?
User::where('id', '=', $value)->first();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor, 2016-01-12
@photosho

1. Are you sure that the function is being called at all? Put echo or dd in it.
2. find finds an entry by primary key. To get only certain fields, you need to pass their names as the second parameter
User::find($value, ["id", "username"]).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question