There are so many useful tricks when it comes with working with Laravel Eloquent. This is one of my favorites. It allows you to simply make a computed attribute on the User model that returns the user’s Gravatar URL. Best part? It’s only a few lines of code. Let’s jump in!
Step 1: Open Your User Model
First, you need to open your user model. In Laravel 8 this should be in the app/Models
directory.
Step 2: Append Gravatar Attribute
All you need to do now is append the attribute for the computed Gravatar URL:
public function getGravatarAttribute()
{
return '<https://www.gravatar.com/avatar/>'.md5( strtolower( trim( $this->email ) ) );
}
What this does is uses the Eloquent syntax to create an attribute. When returned, the field gravatar
will be populated with the URL of the user’s gravatar if they have one. Gravatar returns a default icon if the URL doesn’t map to a user. This is great so you always have an empty state in place when it comes to implementing this in your app.