dongyi6183 2018-03-26 17:53
浏览 702
已采纳

Laravel 5中的加密和解密

I have been looking for ideas on encrypting and decrypting values in Laravel (like VIN Numbers, Employee ID Card Numbers, Social Security Numbers, etc.) and recently found this on the Laravel website: https://laravel.com/docs/5.6/encryption

My question is, how would I print the decrypted values on a blade template? I could see going through the controller and setting a variable and then printing it to a Blade, but I was curious as to how I would also print a decrypted value to an index? Like so...

@foreach($employees as $employee)
{{$employee->decrypted value somehow}}
{{$employee->name}}
@endforeach
  • 写回答

5条回答 默认 最新

  • dongyun4010 2018-03-27 07:20
    关注

    You can handle encrypted attributes with a trait (app/EncryptsAttributes.php):

    namespace App;
    
    trait EncryptsAttributes {
    
        public function attributesToArray() {
            $attributes = parent::attributesToArray();
            foreach($this->getEncrypts() as $key) {
                if(array_key_exists($key, $attributes)) {
                    $attributes[$key] = decrypt($attributes[$key]);
                }
            }
            return $attributes;
        }
    
        public function getAttributeValue($key) {
            if(in_array($key, $this->getEncrypts())) {
                return decrypt($this->attributes[$key]);
            }
            return parent::getAttributeValue($key);
        }
    
        public function setAttribute($key, $value) {
            if(in_array($key, $this->getEncrypts())) {
                $this->attributes[$key] = encrypt($value);
            } else {
                parent::setAttribute($key, $value);
            }
            return $this;
        }
    
        protected function getEncrypts() {
            return property_exists($this, 'encrypts') ? $this->encrypts : [];
        }
    
    }
    

    Use it in your models when necessary:

    class Employee extends Model {
    
        use EncryptsAttributes;
    
        protected $encrypts = ['cardNumber', 'ssn'];
    
    }
    

    Then you can get and set the attributes without thinking about the encryption:

    $employee->ssn = '123';
    {{ $employee->ssn }}
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部