我可以使用Crypt
来加密/解密我的数据。我想加密数据库中的一些信息(例如姓名、电子邮件、电话号码等)。
假设我想加密所有内容,我希望能够通过后台自动执行此操作,这可以通过覆盖create
和save
函数来实现:
// For instance, the save() function could become
public function save(array $options = array())
{
foreach ($this->attributes as $key => $value)
{
if (isset($value)) $this->attributes[$key] = Crypt::encrypt($value);
}
return parent::save($options);
}
现在我希望解密方式保持一致,这样当我使用 User::find($id)
时,返回的 $user
已经被解密。同时,其他函数如 firstOrFail()
、get()
、first()
等也能正常工作。
我还希望当我使用关联查询时也能有相同的功能(例如 User::with('someOtherTable')->find($id)
)。
这种做法可能吗?如果不行,我考虑创建一个辅助函数 decrypt()
。
function decrypt($array)
{
if (!is_array($array)) return Crypt::decrypt($array);
$result = [];
foreach($array as $key => $value) $result[$key] = decrypt($value);
return $result;
}
把我的所有结果都通过这个先处理一遍,然后开始使用它们,但如果Laravel能够提供这个功能,或者有一个“Laravel方式”来实现这个功能就更好了。
User::find(1)
时,在getAttribute()
中被调用的唯一$key
是id
和pivot
。 - Koushareturn Response::json(User::find($id))
作为示例,getAttribute
从未被调用。如果我执行User::find($id)->name
,那么它会被调用。但是我需要从API返回JSON,所以我需要让JSON正常工作?即使是User::find($id)->toJson()
也不会调用它。 - KoushaCrypt::decrypt($this->attributes[$key]);
而不是Crypt::decrypt($this->attributes($key));
因为$this->attributes
是一个数组而不是函数。 - Kousha