Hi All users have avatar butit could be change. But users can chave a collection of avatars and can change if it want. So i created a relationship between model Avatar and Profile and I append avatar_name into my model
protected $appends = [
'avatar_name'
];
public function avatar() {
return $this->hasOne(Avatar::class);
}
public function avatars() {
return $this->hasMany(Avatar::class);
}
public function getAvatarNameAttribute(){
return $this->attributes['avatar_name'] = isset($this->avatar->name) ? $this->avatar->name : null;
}
It works until user change avatar. For example: user has avatar Hello.jpg (id: 1) and he want to change that to World.jpg (id: 2) [id from avatars table]. So after change Profile look like this:
avatar_id: 1,
avatar_name: Hello.jpg
User change the avatar (avatar_id) but avatar_name
will be still this same, so after change this will be look like this:
avatar_id: 2,
avatar_name: Hello.jpg
Why it works that? Would it be possible to makeh avatar_name change dynamically along with avatar_id?
3
Answers
Did you try to add
->latest()
?Example:
Change the conditional operator from this
to this
So the respective line of code will be
Hope this will help you…
In Model