Mau*_*sas 5 php eloquent laravel-4
class Profile extends Eloquent {
protected $fillable = array('name', 'last_name', 'website', 'facebook', 'twitter', 'linkedin', 'google_plus');
public static function boot(){
parent::boot();
self::updating(function($model){
$model->name = Crypt::encrypt($model->name);
$model->last_name = Crypt::encrypt($model->last_name);
$model->facebook = Crypt::encrypt($model->facebook);
$model->twitter = Crypt::encrypt($model->twitter);
$model->linkedin = Crypt::encrypt($model->linkedin);
$model->website = Crypt::encrypt($model->website);
$model->google_plus = Crypt::encrypt($model->google_plus);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我也在使用调用事件..
$user->profile()->update(array(
'name' => e($input['name']),
'last_name' => e($input['last_name']),
'website' => e($input['website']),
'facebook' => e($input['facebook']),
'twitter' => e($input['twitter']),
'linkedin' => e($input['linkedin']),
'google_plus' => e($input['google_plus'])
));
Run Code Online (Sandbox Code Playgroud)
由于某种原因,它没有触发任何事件...我试图在将用户信息保存到数据库之前对其进行加密
我可以建议您使用类似于Accessors & Mutators的解决方案吗?在我看来,出于以下几个原因,这是一个更好的解决方案。例如,您不必担心您的数据当前是否已加密;如果您尝试使用当前的代码,您将在保存之前拥有未加密的数据,并在保存后立即拥有加密的数据,甚至会同时在对象上保存加密和未加密的数据。这可能会导致意想不到的事情发生。假设您有一个像这样的简单方法:
public function index($id) {
$user = User::find($id);
$user->name = 'Raphael';
echo($user->name); // 'Raphael'
$user->save();
echo($user->name); // Encrypted value for 'Raphael'
}
Run Code Online (Sandbox Code Playgroud)
当你调用时你怎么可能知道$user->name
它是否会被加密呢?我的意思是,当然,您可以建立一个约定,仅在保存模型后发送模型,但这似乎是自找麻烦,而且任何小小的疏忽都可能让您头疼。
另一方面,如果您采用此解决方案,您将始终将数据保存为加密的,但不必担心在想要读取数据时解密它,也不必担心在保存之前加密。按照这些思路应该可以解决您的问题:
class Profile extends Eloquent {
protected static $encryptable = ['name', 'last_name', 'website', 'facebook', 'twitter', 'linkedin', 'google_plus'];
public function getAttribute($key) {
$value = parent::getAttribute($key);
if (in_array($key, static::$encryptable)) {
return Crypt::decrypt($value);
}
return $value;
}
public function setAttribute($key, $value) {
if (in_array($key, static::$encryptable)) {
$value = Crypt::encrypt($value);
}
parent::setAttribute($key, $value);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我建议将其转换为 anabstract class
并从中扩展,如果您使用的是 PHP >= 5.4,甚至可以使用 a trait
。