Laravel encrypt cannot encrypt to database when using Update method

谁说胖子不能爱 提交于 2021-02-05 07:52:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!