I am saving the encrypted user data (including user email which is used to login) with Laravel's built in encryption method.
At login, I have to provide encrypted email for authentication but Encryption algorithm generates a different string each time against the same string.
I'm using the following trait for saving encrypted data.
How can I overcome this please?
namespace App\Traits;
use Illuminate\Support\Facades\Crypt;
/**
* Class Encryptable
* @package App\Traits
*/
trait Encryptable
{
/**
* If the attribute is in the encryptable array
* then decrypt it.
*
* @param $key
*
* @return $value
*/
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable) && $value !== '')
$value = Crypt::decrypt($value);
return $value;
}
/**
* If the attribute is in the encryptable array
* then encrypt it.
*
* @param $key
*
* @return $value
*/
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable))
$value = Crypt::encrypt($value);
return parent::setAttribute($key, $value);
}
/**
* When need to make sure that we iterate through
* all the keys.
*
* @return array
*/
public function attributesToArray()
{
$attributes = parent::attributesToArray();
foreach ($this->encryptable as $key)
{
if (isset($attributes[$key]))
$attributes[$key] = Crypt::decrypt($attributes[$key]);
}
return $attributes;
}
}
Usage in User model
namespace App;
use App\Traits\Encryptable;
class User extends Authenticatable implements MustVerifyEmail
{
use Encryptable;
protected $encryptable = [
'first_name',
'sur_name',
'email',
'mobile',
];
}