Adam Anderly

1 min read

Useful Laravel Model Traits: Gravatar

Filed under Laravel, Laravel Traits

Starting a little series here on useful Laravel model traits.

This first one I use quite often.

PHP
// app\Traits\HasGravatar.php
namespace App\Traits;

trait HasGravatar
{
    
    /**
     * The attribute name containing the email address.
     *
     * @var string
     */
    public $gravatarEmail = 'email';
    
    /**
     * Get the model's gravatar
     *
     * @return string
     */
    public function getGravatarAttribute()
    {
        $hash = md5(strtolower(trim($this->attributes[$this->gravatarEmail])));
        return "https://www.gravatar.com/avatar/$hash";
    }

}

It’s a simple trait you can drop onto one of your eloquent models to add gravatar support like so:

PHP
// app\Models\User.php
namespace App\Models;

use App\Traits\HasGravatar

class User
{
    use HasGravatar;
}

Now you can do something like this in your blade views:

PHP
<img src="{{ Auth::user()->gravatar }}">

And you’ll get the gravatar.com URL you’re expecting. No need to create a gravatar column, variable, method, or anything else.

The HasGravatar Trait expects the model to have an email attribute. If your column/attribute is named something other than email simply override the $gravatarEmail property on the HasGravatar trait.

PHP
namespace App\Models;

use App\Traits\HasGravatar

class User
{
    use HasGravatar;

    public $gravatarEmail = 'email_address';
}

Enjoy!

Comments