samedi 18 février 2017

Laravel decrypt attribute based on another attribute

I am trying to save encrypted data into the database based on the user preference. Right now I save in the database the field blood_type as encrypted, but I want to encrypt it only if the user chose that by checking a checkbox which will be saved in the same table under the column encrypted. How can I achieve that by changing the content of this trait ?

My code right now is as follows:

trait Encryptable
{
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        if (in_array($key, $this->encryptable)) {
            $value = Crypt::decrypt($value);
        }

        return $value;
    }

    public function setAttribute($key, $value)
    {
        $this->getAttributeValue("encrypted");

        if (in_array($key, $this->encryptable)) {
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }
}

And the Eloquent model is:

class Information extends Model
{
    protected $table = 'information';

    use Encryptable;

    protected $encryptable = [
        'blood_type'
    ];

    protected $fillable = [
        'first_name',
        'last_name',
        'blood_type',
        'encrypted'
    ];
}

Is there a way to crypt and decrypt the content of blood_type based on the value of encrypted ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2luUibF
via IFTTT

Aucun commentaire:

Enregistrer un commentaire