Rahul Tathod
Rahul Tathod

Reputation: 348

Laravel Encryption/Decryption model data

I am working on a new project that stores guest information. For security I thought it would be cool to store all the personal data in the database with encryption. Is there any specific workflow for doing this. Essentially setting encryption on certain Model fields and having everything just work. Thinking about it, I feel like its not so simple but I thought I would throw it out there.

Upvotes: 0

Views: 3264

Answers (2)

pseudoanime
pseudoanime

Reputation: 1593

This is actually quite straightforward in Laravel. All you have to make sure is that your accessors & mutators(for the properties that you want to encrypt) use the encryption.

More about accessors & mutators here : https://laravel.com/docs/5.6/eloquent-mutators

For example, if you want to encrypt the property email for your model, add the following:

//mutator
public function setEmailAttribute($value)
{

    $this->attributes['email'] = Crypt::encrypt($value);

}


//accessor

public function getNameFirstAttribute($value)
{
    if (is_null($value)) {

        return $value;

    }

    return Crypt::decrypt($value);
}

Upvotes: 2

nirmeets
nirmeets

Reputation: 33

You can use accessors and mutators. They will encrypt data when you store the data and decrypt it when you fetch by itself.

Upvotes: 1

Related Questions