问题
Hi i want to encrypt some field in database when user create or edit data. IF create, the encryption work, but when user edit data, the value that save in database will be normal text not encrypted
<?php
namespace App\Traits;
use Crypt;
trait Encryptable
{
public function toArray()
{
$array = parent::toArray();
foreach ($array as $key => $attribute) {
if (in_array($key, $this->encryptable) && $array[$key]!='') {
try {
$array[$key] = Crypt::decrypt($array[$key]);
} catch (\Exception $e) {
}
}
}
return $array;
}
public function getAttribute($key)
{
try {
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable) && $value!='') {
$value = Crypt::decrypt($value);
return $value;
}
return $value;
} catch (\Exception $e) {
return $value;
}
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
}
and I declare which field need to encrypt in model
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Encryptable;
class PraApplication extends Model
{
use Encryptable;
protected $table = 'praapplications';
protected $fillable = ['fullname','icnumber','phone','email'];
protected $encryptable = ['icnumber', 'phone','email'];
}
来源:https://stackoverflow.com/questions/64531702/laravel-encrypt-cannot-encrypt-to-database-when-using-update-method