I use Laravel 6 and I want access to avatar attribute from user when I use posts() relation.
User model:
/**
* @var array
*/
protected $appends = [
'avatar',
];
/**
* @return HasMany
*/
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
/**
* @return string
*/
public function getAvatarAttribute(): string
{
return sprintf('https://secure.gravatar.com/avatar/%s?s=500', md5($this->email));
}
The code of my controller:
$topic = Topic::where('slug', $slug)->firstOrFail();
foreach ($topic->posts()->get() as $post) {
dd($post->user->avatar); // return null
}
Post model:
/**
* @return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
I get the name of user with $post->user->name
but avatar attribute is not called.