Skip to content

Instantly share code, notes, and snippets.

@peterbrinck
Forked from Sammyjo20/EncryptedJson.php
Created October 22, 2020 11:30
Show Gist options
  • Save peterbrinck/0a8c6427572db5e522a5b04f00dc3dc5 to your computer and use it in GitHub Desktop.
Save peterbrinck/0a8c6427572db5e522a5b04f00dc3dc5 to your computer and use it in GitHub Desktop.
EncryptedJson Cast
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class EncryptedJson implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed
*/
public function get($model, $key, $value, $attributes)
{
$decrypted = rescue(function () use ($value) {
return decrypt($value);
});
return json_decode($decrypted, true);
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed|string
*/
public function set($model, $key, $value, $attributes)
{
return encrypt(json_encode($value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment