AmarjaPatil4
AmarjaPatil4

Reputation: 1650

How to set append variable on condition in laravel model?

I am doing project in Laravel. I have model named 'User.php' and here I want to set $appends variable depends on condition. In database I have stored values in key attribute format. eg:

user.php looks like

class User extends Authenticatable
{
protected $appends = ['avatar_photo'];

public function profile_attributes()
    {
        return $this->belongsToMany(\App\Models\Access\User\UserProfileAttributes::class,config('access.user_attribute_values_table'),'user_id','user_attribute_id')->withPivot('value', 'active')->withTimestamps();
    }

/**
     * @return string
     */
    public function getAvatarPhotoAttribute()
    {
        $avatar = $this->profile_attributes()->where('user_attributes_master.id',7)->first()->avatar_path;
        return $avatar;

    }
}

Here I get avatar_path attribute to every record which is append variable I have set to profile.php model. How to get this to only 'avatar' col of profile.php. How can I set this appends variable.

attribute model conatins code,

protected $appends = ['avatar_path','theme_path'];

public function getAvatarPathAttribute()
    {
            return $this->pivot->value != null ? config('app.url').'/'.config('profile.images.user_images'). "/" . $this->pivot->user_id ."/" . config("profile.images.avatar")."/".$this->pivot->value : '';

    }

Here I dont want 'avatar_path' for every attribute.

Upvotes: 1

Views: 8187

Answers (2)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

You can use appends() to dynamically add attributes to $appends. Try this:

$attributes->where('pivot.value', '!=', null)->each->appends('avatar_path');

Upvotes: 2

Leo
Leo

Reputation: 7420

rename: protected $appends = ['avatar_photo'];

to : 'protected $appends = ['avatarphoto'];'

Upvotes: 0

Related Questions