Starting a little series here on useful Laravel model traits.
This first one I use quite often.
// 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:
// 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:
<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.
namespace App\Models; use App\Traits\HasGravatar class User { use HasGravatar; public $gravatarEmail = 'email_address'; }
Enjoy!