Skip to content

Instantly share code, notes, and snippets.

@Elshaden
Created November 8, 2020 07:58
Show Gist options
  • Save Elshaden/d0d4641898647d3925966f6ecdbe6fab to your computer and use it in GitHub Desktop.
Save Elshaden/d0d4641898647d3925966f6ecdbe6fab to your computer and use it in GitHub Desktop.
Encrypt any Field in Database , using setter and getter in Laravel model implemented as cast
namespace App\Models\Casts;
/*
* Usage
*
* First use the Class
*
* use App\Models\Casts\EncryptCast;
*
*
*
protected $casts = [
'token' => EncryptCast::class,
'card => EncryptCast::class,
];
*/
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class EncryptCast implements CastsAttributes
{
/**
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed|null
*/
public function get($model, string $key, $value, array $attributes)
{
return ! is_null($value) ? decrypt($value) : null;
}
/**
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed|null[]
*/
public function set($model, string $key, $value, array $attributes)
{
return [$key => ! is_null($value) ? encrypt($value) : null];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment