laravel - display avatar if user upload it or use default image
I am allowing user to upload an avatar (profile image) in their profile. While uploading avatar is entirely optional, if user does not have avatar, a default image will be used. However, checking whether a user has an avatar uploaded or not in my
I understand my user info is null but why would it throw the error since if it's null then it shall execute the else statement and display the default image..?
@wakanda not a very DRY way of doing that TBH. all you need to do is alter the image src not duplicate the image tag. As @tykus answer best demonstrates.
/**
* Get the author of the post.
*/
public function userInfo()
{
return $this->hasOne(UserInfo::class)->withDefault([
'avatar' => 'default.jpeg'
]);
}
Given userInfo is a relationship on the User model (which wasn't clear from your original post), then this returns a default object from an otherwise null relation:
public function userInfo()
{
return $this->hasOne(UserInfo::class)->withDefault([
'avatar' => 'default.jpeg'
]);
}
Either one works. If you need a default UserInfo model in other circumstances then the relationship approach is likely preferable. However, sometimes you may want a null result for the relationship which this will prevent. It is really up to each individual use case.