Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nshd09's avatar

Encrypting model data

I have created trait and using model but still its inserting plain text without any encryption.

My Trait:

0 likes
2 replies
Tray2's avatar

When I want to change the data before insert I add a setAttribute method to my model

public function setTitleAttribute($value)
    {
        $this->attributes['title'] = ucwords(strtolower($value));
    }

This one enforcing that all words in the title starts with an uppercase.

So something like

public function setTitleAttribute($value)
{
    $this->attributes['title'] = encrypt($value));
}

public function getTitleAttribute($value)
{
    return decrypt($value);
}

Should do the trick.

Snapey's avatar

Go for an off the shelf package. There are lots of aspects to consider such as when your model is accessed as an array for instance

Try https://packagist.org/packages/austinheap/laravel-database-encryption

I did my own trait previously, but not sure if I would again.

<?php

namespace App\ModelTraits;

use Illuminate\Support\Facades\Crypt;

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

        if(is_null($value)){
            return;
        }

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

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

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

    public function getArrayableAttributes()
    {
        $attributes = parent::getArrayableAttributes(); // call the parent method

        foreach ($this->encryptable as $key) {

            if (isset($attributes[$key])) {

                $attributes[$key] = Crypt::decryptString($attributes[$key]);

            }
        }
        return $attributes;
    }


}

The above does the job when added to a model but there are things it does not do.

To use the above, add the trait to a model then add an array of attributes that should be encrypted, eg

   public $encryptable = ['surname','knownas','daytimePhone','eveningPhone','mobilePhone', 'spouse','classification','address1', 'address2', 'town', ' county', 'postcode'];

You also have to realise that you cannot encrypt a user's email address without screwing up login, you cannot search within encrypted data, and you cannot sort encrypted data unless you can load the whole collection into memory at once.

Please or to participate in this conversation.