I have been looking for ideas on encrypting and decrypting values in Laravel (like VIN Numbers, Employee ID Card Numbers, Social Security Numbers, etc.) and recently found this on the Laravel website: https://laravel.com/docs/5.6/encryption
My question is, how would I print the decrypted values on a blade template? I could see going through the controller and setting a variable and then printing it to a Blade, but I was curious as to how I would also print a decrypted value to an index? Like so...
@foreach($employees as $employee)
{{$employee->decrypted value somehow}}
{{$employee->name}}
@endforeach
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With