How do I implement Gravatar in Laravel?
Asked Answered
V

2

27

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.

Vigilantism answered 18/5, 2014 at 17:34 Comment(0)
V
66

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.

Vigilantism answered 18/5, 2014 at 17:34 Comment(0)
S
12

Expanding on Wogan's answer a bit...

Another example using a Trait:

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";
    }

}

Now on a given model (i.e. User) where you want to support Gravatar, simply import the trait and use it:

use App\Traits\HasGravatar;

class User extends Model
{
    use HasGravatar;
}

If the model doesn't have an email column/attribute, simply override the default by setting it in the constructor of your model like so:

public function __construct() {
    // override the HasGravatar Trait's gravatarEmail property
    $this->gravatarEmail = 'email_address';
}
Scribner answered 27/8, 2016 at 7:47 Comment(2)
Excellent! Yeah I'd definitely recommend a Trait-based approach now, after working with Laravel for two years. Thanks for sharing @anderly!Vigilantism
Really grateful for the excellent answers. Respect for you both!Sniffle

© 2022 - 2024 — McMap. All rights reserved.