SquareNetMedia's avatar

Spatie Media Library & Larvel 9

I am using Spatie Media Library Pro and Laravel 9.

I am wanting to allow the user to upload an avatar but if they dont I want to use a defult in its place.

I was thinking of using the following function - to either display what has been uploaded and is stored in the media table or to display a default

public function getAvatarAttribute()
    {
        if (FILE EXISTS) {
            $avatar = $this->getFirstMedia('avatars')->first()->getUrl('');
        } else {
            $avatar = asset('/img/placeholders/default.png');
        }

        return $avatar;
    }

But struggling with how to check if the user has uploaded an image in the db.

0 likes
2 replies
tisuchi's avatar

@squarenetmedia You can check if the user has uploaded an avatar by checking if the user has any media items associated with the "avatars" collection. Here's an example of how you can check if the user has an avatar and return the appropriate URL:

public function getAvatarAttribute()
{
    if ($this->hasMedia('avatars')) {
        $avatar = $this->getFirstMedia('avatars')->getUrl();
    } else {
        $avatar = asset('/img/placeholders/default.png');
    }

    return $avatar;
}

This code uses the hasMedia() method to check if the user has any media items associated with the "avatars" collection. If they do, it uses the getFirstMedia() method to get the first media item associated with that collection and then getUrl() method to get the URL of that media item. If the user does not have any media items associated with the "avatars" collection, it will return the URL of the default image.

1 like

Please or to participate in this conversation.