我一直在寻找有关在 Laravel 中加密和解密值的想法(例如 VIN 号、员工 ID 卡号、社会保障号等),最近在 Laravel 网站上发现了这一点:https://laravel.com/docs/5.6/加密
我的问题是,如何在刀片模板上打印解密的值?我可以看到通过控制器并设置一个变量,然后将其打印到 Blade,但我很好奇如何将解密的值打印到索引?就像这样...
@foreach($employees as $employee)
{{$employee->decrypted value somehow}}
{{$employee->name}}
@endforeach
您可以使用特征(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 : [];
}
}
必要时在您的模型中使用它:
class Employee extends Model {
use EncryptsAttributes;
protected $encrypts = ['cardNumber', 'ssn'];
}
然后你就可以获取和设置属性而无需考虑加密:
$employee->ssn = '123';
{{ $employee->ssn }}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)