Skip to content

Instantly share code, notes, and snippets.

@sanampatel
Last active April 24, 2021 15:39
Show Gist options
  • Select an option

  • Save sanampatel/0672c4ad407ea132f5e273bc0e6d09e9 to your computer and use it in GitHub Desktop.

Select an option

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.
<?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'
];
}
*/
@sanampatel
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment