Laravel Eloquent - 加密/解密数据

Kou*_*sha 14 encryption laravel eloquent laravel-4

我可以Crypt用来加密/解密我的数据.我想加密我的数据库中的一些信息(例如名称,电子邮件,电话号码等).

假设我想要一切加密,我希望能够在后台自己完成这个,我可以通过覆盖createsave函数来执行:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

现在,我希望解密以相同的方式执行,因此当我说User::find($id),返回$user已经解密.还有其他功能,例如firstOrFail() get() first()和所有功能.

当我使用关系时,我也希望扩展这个功能(所以User::with('someOtherTable')->find($id)也工作).

这可能吗?如果这是不可能的,我正在考虑创建一个辅助函数decyrpt()

function decrypt($array)
{
    if (!is_array($array)) return Crypt::decrypt($array);

    $result = [];

    foreach($array as $key => $value) $result[$key] = decrypt($value);

    return $result;
}
Run Code Online (Sandbox Code Playgroud)

并且首先通过我的所有结果,然后开始使用它们,但是如果Laravel提供这个,或者如果有一个"Laravel方式"这样做会更好.

Jos*_*ber 16

加密一切并没有多大意义.例如,您永远不想加密主键; 这甚至没有意义.同样,您可能不想加密日期字段; 你将失去对它们执行任何类型的SQL查询的能力.

考虑到这一点,你可以尝试这样的事情:

class BaseModel extends Eloquent {

    protected $encrypt = [];

    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encrypt))
        {
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }

    public function getAttribute($key)
    {
        if (in_array($key, $this->encrypt))
        {
            return Crypt::decrypt($this->attributes[$key]);
        }

        return parent::getAttribute($key);
    }

    public function attributesToArray()
    {
        $attributes = parent::attributesToArray();

        foreach ($attributes as $key => $value)
        {
            if (in_array($key, $this->encrypt))
            {
                $attributes[$key] = Crypt::decrypt($value);
            }
        }

        return $attributes;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后让所有模型扩展此模型,并将$encrypt属性设置为您希望为该特定模型加密的任何列.


PS如果你想使用Eloquent的访问器功能,你将不得不更多地使用它.