Reputation: 1650
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:
I have table named 'user' which contains basic info like name, email and mobile number.
Other table named as 'user_attributes_master' which contains columns like 'avatar', 'theme', etc.
and other table named as 'user_attribute_values' which contains columns like 'id', 'user_id' and 'att_id'(which is a primary key of user_attributes_master table)
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
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
Reputation: 7420
rename: protected $appends = ['avatar_photo'];
to : 'protected $appends = ['avatarphoto'];'
Upvotes: 0