andybeak
1/23/2017 - 11:51 AM

Encryptable Trait for Laravel

Encryptable Trait for Laravel

<?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',
    ];
}
<?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);
    }
}