Wog*_*gan 16 php gravatar laravel-4
在Laravel中实施Gravatar URL的最快方法是什么?我有一个强制性的电子邮件地址字段,但我不想为Gravatars创建一个新列,我更喜欢使用本机Auth::user()属性.
Wog*_*gan 42
事实证明,您可以使用Laravel mutator来创建模型中不存在的属性.假设您在相应的表中有一个User带有必填email列的模型users,只需将其粘贴在您的User模型中:
public function getGravatarAttribute()
{
$hash = md5(strtolower(trim($this->attributes['email'])));
return "http://www.gravatar.com/avatar/$hash";
}
Run Code Online (Sandbox Code Playgroud)
现在,当你这样做:
Auth::user()->gravatar
Run Code Online (Sandbox Code Playgroud)
您将获得您期望的gravatar.com网址.无需创建gravatar列,变量,方法或其他任何内容.
扩大了Wogan的答案......
另一个使用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";
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在您想要支持Gravatar的给定模型(即用户)上,只需导入特征并使用它:
use App\Traits\HasGravatar;
class User extends Model
{
use HasGravatar;
}
Run Code Online (Sandbox Code Playgroud)
如果模型没有email列/属性,只需通过在模型的构造函数中设置它来覆盖默认值,如下所示:
public function __construct() {
// override the HasGravatar Trait's gravatarEmail property
$this->gravatarEmail = 'email_address';
}
Run Code Online (Sandbox Code Playgroud)