Go for an off the shelf package. There are lots of aspects to consider such as when your model is accessed as an array for instance
Try
https://packagist.org/packages/austinheap/laravel-database-encryption
I did my own trait previously, but not sure if I would again.
<?php
namespace App\ModelTraits;
use Illuminate\Support\Facades\Crypt;
trait EncryptableTrait
{
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if(is_null($value)){
return;
}
if (in_array($key, $this->encryptable)) {
$value = Crypt::decryptString($value);
}
return $value;
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = Crypt::encryptString($value);
}
return parent::setAttribute($key, $value);
}
public function getArrayableAttributes()
{
$attributes = parent::getArrayableAttributes(); // call the parent method
foreach ($this->encryptable as $key) {
if (isset($attributes[$key])) {
$attributes[$key] = Crypt::decryptString($attributes[$key]);
}
}
return $attributes;
}
}
The above does the job when added to a model but there are things it does not do.
To use the above, add the trait to a model then add an array of attributes that should be encrypted, eg
public $encryptable = ['surname','knownas','daytimePhone','eveningPhone','mobilePhone', 'spouse','classification','address1', 'address2', 'town', ' county', 'postcode'];
You also have to realise that you cannot encrypt a user's email address without screwing up login, you cannot search within encrypted data, and you cannot sort encrypted data unless you can load the whole collection into memory at once.