Laravel 5中的加密和解密

Mat*_*hew 4 php encryption laravel laravel-5

我一直在寻找有关在Laravel中加密和解密值(例如VIN号,员工身份证号,社会保险号等)的想法,最近在Laravel网站上发现了这一点:https ://laravel.com/docs/5.6 /加密

我的问题是,如何在刀片模板上打印解密的值?我可以看到遍历控制器并设置了一个变量,然后将其打印到Blade中,但是我很好奇如何将解密后的值打印到索引中?像这样

@foreach($employees as $employee)
{{$employee->decrypted value somehow}}
{{$employee->name}}
@endforeach
Run Code Online (Sandbox Code Playgroud)

Jon*_*eir 6

您可以使用特征(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 : [];
    }

}
Run Code Online (Sandbox Code Playgroud)

必要时在模型中使用它:

class Employee extends Model {

    use EncryptsAttributes;

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

}
Run Code Online (Sandbox Code Playgroud)

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

$employee->ssn = '123';
{{ $employee->ssn }}
Run Code Online (Sandbox Code Playgroud)