Wogan Wogan - 3 months ago 14
PHP Question

How do I implement Gravatar in Laravel?

What's the fastest way to implement Gravatar URLs in Laravel? I have a mandatory email address field, but I don't want to create a new column for Gravatars, and I'd prefer to use the native

Auth::user()
attributes.

Answer

Turns out, you can use a Laravel mutator to create attributes that don't exist in your model. Assuming you have a User model with a mandatory email column in the corresponding users table, just stick this in your User model:

public function getGravatarAttribute()
{
    $hash = md5(strtolower(trim($this->attributes['email'])));
    return "http://www.gravatar.com/avatar/$hash";
}

Now when you do this:

Auth::user()->gravatar

You'll get the gravatar.com URL you're expecting. Without creating a gravatar column, variable, method, or anything else.