Created
December 17, 2020 00:38
-
-
Save guywarner/b85b29425bc90a245fb9648d32c5f709 to your computer and use it in GitHub Desktop.
Laravel auto encrypt trait
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
<?php | |
namespace App\Traits; | |
use Crypt; | |
trait Encryptable | |
{ | |
/** | |
* Get a models attribute on select | |
* | |
* @param string $key | |
* @return mixed | |
*/ | |
public function getAttribute($key) | |
{ | |
$value = parent::getAttribute($key); | |
if (in_array($key, $this->encryptable)) { | |
try { | |
$value = Crypt::decrypt($value); | |
} catch (\Exception $e) { | |
return $value; | |
} | |
} | |
return $value; | |
} | |
/** | |
* Set a models attribute on save | |
* | |
* @param string $key | |
* @param string|null $value | |
* @return mixed | |
*/ | |
public function setAttribute($key, $value) | |
{ | |
if (is_null($value)) { | |
$value = ""; | |
} | |
if (in_array($key, $this->encryptable) && $value != "") { | |
$value = Crypt::encrypt($value); | |
} | |
return parent::setAttribute($key, $value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment