Skip to content

Instantly share code, notes, and snippets.

@guywarner
Created December 17, 2020 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guywarner/b85b29425bc90a245fb9648d32c5f709 to your computer and use it in GitHub Desktop.
Save guywarner/b85b29425bc90a245fb9648d32c5f709 to your computer and use it in GitHub Desktop.
Laravel auto encrypt trait
<?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