且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 5中的加密和解密

更新时间:2023-02-22 14:41:17

您可以处理带有特征(app/EncryptsAttributes.php)的加密属性:

You can handle encrypted attributes with a trait (app/EncryptsAttributes.php):

namespace App;

trait EncryptsAttributes {

    public function attributesToArray() {
        $attributes = parent::attributesToArray();
        foreach($this->getEncrypts() as $key) {
            if(array_key_exists($key, $attributes)) {
                $attributes[$key] = decrypt($attributes[$key]);
            }
        }
        return $attributes;
    }

    public function getAttributeValue($key) {
        if(in_array($key, $this->getEncrypts())) {
            return decrypt($this->attributes[$key]);
        }
        return parent::getAttributeValue($key);
    }

    public function setAttribute($key, $value) {
        if(in_array($key, $this->getEncrypts())) {
            $this->attributes[$key] = encrypt($value);
        } else {
            parent::setAttribute($key, $value);
        }
        return $this;
    }

    protected function getEncrypts() {
        return property_exists($this, 'encrypts') ? $this->encrypts : [];
    }

}

必要时在模型中使用它:

Use it in your models when necessary:

class Employee extends Model {

    use EncryptsAttributes;

    protected $encrypts = ['cardNumber', 'ssn'];

}

然后,您无需考虑加密即可获取和设置属性:

Then you can get and set the attributes without thinking about the encryption:

$employee->ssn = '123';
{{ $employee->ssn }}