Naysoewin's avatar

Toggle Local Avatar and Socialite Avatar

Hello,

Before it's working fine , If user doesn't have image upload , show default avatar link as below


    public function getAvatarPathAttribute($avatar)
    {
        return $avatar ? asset('storage/' . $avatar) : 'https://www.gravatar.com/avatar/';
    }

After added socialite package and someone try to login with socialite (ex.github), we request user avatar and insert to avatar_path column with full URL like that

https://avatars3.githubusercontent.com/u/62180549?v=4

So the image doesn't render anymore who login with socialite .

Browser inspect , src Url is like that src="http://localhost:8000/storage/https://avatars3.githubusercontent.com/u/62180549?v=4"

Please let me know how can i toggle it. Thanks

0 likes
5 replies
bobbybouwmann's avatar

Well, take another look at the "src" value. You're appending a URL behind a URL. That will never work. Instead, you need to do something like this

public function getAvatarPathAttribute($avatar)
{
    return $avatar ?? 'https://www.gravatar.com/avatar/';
}

Since $avatar is already an URL, you can simply return that ;)

1 like
Naysoewin's avatar

Hi @bobbybouwmann ,

Thank you so much ,

it's work for this two condition , (1) if user login with Social and get their image as url (2) If User doesn't have image upload we show default link gravatar.com

But , it doesn't work for if user upload manually via local server because return only avatar_path value like that

src="avatars/TzO3VaW8nSv2Al3Hz5r8J26beilnPACFAdySiDdf.png"

Could you help me check again for me? Thanks again

bobbybouwmann's avatar
Level 88

Check, well in that case you probably need to check if path is an URL or not and based on that perform your action.

Try this

public function getAvatarPathAttribute($avatar)
{
    // Check if the value is a URL (you can also do this with a regex for a better comparison)
    if (filter_var($avatar, FILTER_VALIDATE_URL)) {
        return $avatar;
    }

    // No URL and not empty, so it's a path
    if ($avatar !== null) {
        return asset('storage/' . $avatar);
    }

    // If nothing matches, we return the default
    return 'https://www.gravatar.com/avatar/';
}
1 like

Please or to participate in this conversation.