Last active
April 8, 2016 14:36
-
-
Save arondeparon/3cd905c5fbda39a3461d1cb5eaef9ed4 to your computer and use it in GitHub Desktop.
Laravel casted encrypted attributes
This file contains hidden or 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\Models; | |
use Crypt; | |
use Illuminate\Database\Eloquent\Model; | |
/** | |
* This model implements a custom cast named (en)crypt. If a property is added to | |
* the cast array with this type, the value will be automatically and transparently encrypted | |
* on storage and decrypted on retrieval. | |
* | |
* Implementing is as easy as adding the following property to an implementing model: | |
* | |
* protected $casts = [ | |
* 'my_awesome_secret_property' => 'crypt' | |
* ]; | |
* | |
*/ | |
class BaseModel extends Model | |
{ | |
/** | |
* Cast an attribute to a native PHP type. | |
* | |
* @param string $key | |
* @param mixed $value | |
* @return mixed | |
*/ | |
protected function castAttribute($key, $value) | |
{ | |
$castValue = parent::castAttribute($key, $value); | |
if ($castValue == $value) { | |
// check our additional cast options | |
switch ($this->getCastType($key)) { | |
case 'crypt': | |
case 'encrypt': | |
return Crypt::decrypt($value); | |
default: | |
return $value; | |
} | |
} | |
return $castValue; | |
} | |
/** | |
* Set a given attribute on the model. | |
* | |
* @param string $key | |
* @param mixed $value | |
* @return $this | |
*/ | |
public function setAttribute($key, $value) | |
{ | |
parent::setAttribute($key, $value); | |
if ($this->isEncryptable($key)) { | |
$this->attributes[$key] = Crypt::encrypt($value); | |
} else { | |
$this->attributes[$key] = $value; | |
} | |
return $this; | |
} | |
/** | |
* Check whether an attribute should be encrypted | |
* | |
* @param $key | |
* @return bool | |
*/ | |
protected function isEncryptable($key) | |
{ | |
return $this->hasCast($key, ['encrypt', 'crypt']); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment