Corbin's avatar

How do I decrypt an encrypted mutator in a JSON output?

What I'm trying to do is encrypt and decrypt data using mutators. The problem I'm having is that I am trying to have my value decrypt on output for a JSON api. The problem is when I output these values in the controller they're still encrypted. I was trying to figure out how to use transform on the collection, but gave up. I'm not sure I can use transform if I intend to paginate the out put as well.

Encryptable.php

<?php

namespace App;

use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

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

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

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

Model

class Patient extends Model
{
    use Encryptable;

    protected $encryptable = [
        'blood_type',
        'medical_conditions',
        'allergies',
        'emergency_contact_id',
    ];
}

Controller

public index(Patient $patient)
{
    return $patient->orderBy('created_at','DESC')->get();
}

Thanks for any help

0 likes
3 replies
ftiersch's avatar
ftiersch
Best Answer
Level 28

The accessors and mutators are only called when you use the variable explicitly.

You could use a Resource for your Patient and inside there it would be called explicitly and decrypted automatically. Also with that you will have finer control what values are actually returned (if you are using an API here).

Another possibility would be to use Eloquent events (saving and retrieved maybe?) to only encrypt the values while writing them to the database because I guess in your code you don't need the encrypted values?

Corbin's avatar

Awesome, thank you. I created an API resource and it worked great.

Please or to participate in this conversation.