Created
November 8, 2020 07:58
-
-
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
This file contains 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
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