I am encrypting/decrypting the DB field values in Laravel through accessors and mutators, which is working fine in normal eloquent transactions.
class Person extends Model
{
use Notifiable;
protected $table = 'person';
public function getFirstNameAttribute($value)
{
return Crypt::decryptString($value);
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = array();
protected function user()
{
return $this->belongsTo('App\Models\User', 'useraccount_id', 'id');
}
}
But the encryption and decryption not working under the following conditions
- Eloquent relationships
- DB raw queries
Working
$person = Person::find($person_id);
$person->firstName;
Not Working
$user = User::find($user_id);
$user->person->firstName;
You would probably have the encryption at the database level, as if someone gets access to the database you don’t want them to be able to read people’s medical data in plain text.
You could create a trait that encrypts and decrypts data on save and retrieval respectively:
You can then just apply the trait to your models, and define a property called $encryptable that’s an array of columns whose data should be encrypted:
You can do it with laravel's Crypt Facades. please follow this example.
I implemented from this article link : https://hackthestuff.com/article/laravel6-encryption-and-decryption-model-data-using-crypt-class
Based on Iman his answer i changed the trait so it works with the casts array from Laravel self.