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!
First, you need to open your user model. In Laravel 8 this should be in the app/Models
directory.
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.
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.
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!
Professional developers choose Server Side Up to ship quality applications without surrendering control. Explore our tools and resources or work directly with us.
We're a community of 3,000+ members help each other level up our development skills.
Active Discord Members
We help each other through the challenges and share our knowledge when we learn something cool.
Stars on GitHub
Our community is active and growing.
Newsletter Subscribers
We send periodic updates what we're learning and what new tools are available. No spam. No BS.
Be the first to know about our latest releases and product updates.