Skip to content

Instantly share code, notes, and snippets.

@andybeak
Created January 23, 2017 11:51
Show Gist options
  • Save andybeak/64dc056b774a6eb2c1bbb1cb3b6029f6 to your computer and use it in GitHub Desktop.
Save andybeak/64dc056b774a6eb2c1bbb1cb3b6029f6 to your computer and use it in GitHub Desktop.
Encryptable Trait for Laravel
<?php
/**
* This trait applies accessors and mutators to a model attributes if the config setting to encrypt data at rest is on
*/
namespace App\Lib\Domain\Models;
use Config;
use Crypt;
/**
* Class Encryptable
*
* @package App\Lib\Domain\Models
*/
trait Encryptable
{
/**
* Accessor - decrypts the value
*
* @access public
* @param $key
*/
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable) && Config::get('app.encrypt_data_at_rest')) {
$value = Crypt::decrypt($value);
}
return $value;
}
/**
* Mutator - encrypts the value
*
* @access public
* @param $key
* @param $value
* @return mixed
*/
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable) && Config::get('app.encrypt_data_at_rest')) {
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
}
<?php namespace App\Lib\Domain\Models;
use Illuminate\Database\Eloquent\Model;
class UserDetail extends Model
{
use Encryptable;
protected $encryptable = [
'title',
'salute',
'name_first',
'name_last',
'address_line_1',
'address_line_2',
'address_line_3',
'city',
'county',
'country',
'postcode',
'landline',
'mobile',
'email_address',
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment