skip to Main Content

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


  1. Did you try to add ->latest()?

    Example:

    public function avatar() {
        return $this->hasOne(Avatar::class)->latest();
    }
    
    Login or Signup to reply.
  2. Change the conditional operator from this

    isset($this->avatar->name) ? $this->avatar->name : null;
    

    to this

    isset($this->avatar_name) ? $this->avatar_name : null;
    

    So the respective line of code will be

    public function getAvatarNameAttribute(){
        return $this->attributes['avatar_name'] = isset($this->avatar_name) ? $this->avatar_name : null;
    }
    

    Hope this will help you…

    Login or Signup to reply.
  3. In Model

    public function avatar() {
        return $this->hasOne(Avatar::class); // return first avatar
        // or
        return $this->hasOne(Avatar::class)->latest(); // return last avatar
    }
    
    
    protected $appends = ['avatar_name'];
    protected $hidden = ['avatar'];
    
    public function getAvatarNameAttribute(){
        return $this->avatar->name ?? null; // PHP 7.4 and above version
        // else
        return isset($this->avatar->name) ? $this->avatar->name : null;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search