Last active
April 24, 2021 15:39
-
-
Save sanampatel/0672c4ad407ea132f5e273bc0e6d09e9 to your computer and use it in GitHub Desktop.
EncryptAble PHP Trait to encryptable values while storing to database and decrypt when retrieved.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Traits; | |
| use Illuminate\Support\Facades\Crypt; | |
| trait EncryptAble | |
| { | |
| /** | |
| * If the attribute is in the encryptable array | |
| * then decrypt it. | |
| * | |
| * @param $key | |
| * | |
| * @return $value | |
| */ | |
| public function getAttribute($key) | |
| { | |
| $value = parent::getAttribute($key); | |
| if (in_array($key, $this->encryptable) && $value !== '') { | |
| $value = Crypt::decryptString($value); | |
| } | |
| return $value; | |
| } | |
| /** | |
| * If the attribute is in the encryptable array | |
| * then encrypt it. | |
| * | |
| * @param $key | |
| * @param $value | |
| */ | |
| public function setAttribute($key, $value) | |
| { | |
| if (in_array($key, $this->encryptable)) { | |
| $value = Crypt::encryptString($value); | |
| } | |
| return parent::setAttribute($key, $value); | |
| } | |
| /** | |
| * When need to make sure that we iterate through | |
| * all the keys. | |
| * | |
| * @return array | |
| */ | |
| public function attributesToArray() | |
| { | |
| $attributes = parent::attributesToArray(); | |
| foreach ($this->encryptable as $key) { | |
| if (isset($attributes[$key])) { | |
| $attributes[$key] = Crypt::decryptString($attributes[$key]); | |
| } | |
| } | |
| return $attributes; | |
| } | |
| } | |
| /* | |
| In model import the trait | |
| use App\Traits\EncryptAble; | |
| class Post extends Model | |
| { | |
| use EncryptAble; | |
| protected $encryptable = [ | |
| 'secret_data' | |
| ]; | |
| } | |
| */ |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refer to this links as well :
https://stackoverflow.com/questions/48785932/encrypt-decrypt-db-fields-in-laravel
https://laracasts.com/discuss/channels/laravel/encrypting-model-data