How do I implement Gravatar in Laravel?

后端 未结 2 915
走了就别回头了
走了就别回头了 2021-01-31 18:30

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

2条回答
  •  余生分开走
    2021-01-31 19:26

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

提交回复
热议问题