Append Gravatar Attribute to the Laravel Eloquent User Model
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.
You can now reference this value from within Laravel and in Blade templates as:
$user->gravatar;
However, if you are not using Blade templates or loading your User through an API, see below.
Step 3: (OPTIONAL) Append Gravatar Value to Array
The reason this is optional is it only matters if you are loading your User resource through an API or some serialized format. If you are using Laravel blade, you won’t be interacting much with your User Model in a serialized form (JSON or Array), so you can use the attribute through:
$user->gravatar;
However, since it’s a computed attribute, you will have to add this to your $appends
array on your model. When your resource is loaded through an API, the gravatar
field will appear in the JSON for that user. All you have to do is add the following to your User Model:
protected $appends = [
'gravatar'
];
If the $appends
array already exists, just add gravatar
. Now you can access user.gravatar
when returned in JSON or if you convert your model to an array within your Laravel application.
Conclusion
I love these computed attributes and how simple they are to add useful functionality to your app. The reason I choose to do a computed Gravatar URL instead of saving it to the database is there really isn’t any need to save the URL since it’s easily computed and keeps our database tidy. It also stays up-to-date if the user changes their email. If you have any thoughts or questions, feel free to reach out in the comment section below!